Java 网络编程
如何实现网络中的主机互相通信(两个必须因素):
1)通信双方的地址
IP:电脑主机的地址
端口号:主机中的哪个应用程序
2)一定的规则(即网络通信协议)
IP和端口号:
1.ip:唯一的标识Internet上的计算机通信实体
2.在Java中使用InetAddress类代表IP
3.IP分类:IPv4和IPv6;万维网和局域网
4.域名:www.google.com
5.本地回路地址:127.0.0.1 或者localhost
6.如何实例化InetAddress:两个方法:getByName(String host),getLocalHost(),两个常用方法:getHostName()/getHostAddress()
7.端口号:正在计算机上运行的进程
要求:不同的进程有不同的端口号
范围:被规定为一个16位的整数:0~65535
8.端口号与IP地址的组合得出一个网络套接字:socket
TCP/IP协议
TCP:“三次握手” “四次挥手” 安全性高,效率低
UDP:不需要建立连接就可以发送,速度快
* 实现TCP的网络编程 例子1:客户端发送信息给服务端 */ public class TCPTest1 { //客户端 @Test public void client(){ InetAddress inet = null; OutputStream os = null; Socket socket = null; try { //1.创建socket对象,指明服务器的ip和端口号 inet = InetAddress.getByName("127.0.0.1"); socket = new Socket(inet,8889); //2.获取输出流 os = socket.getOutputStream(); //3.写出数据 os.write("hello from TCP socket".getBytes()); } catch (Exception e) { e.printStackTrace(); }finally{ //4.关闭资源 if(os != null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if(socket != null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } //服务端 @Test public void server(){ ServerSocket ss = null; Socket socket = null; InputStream is = null; ByteArrayOutputStream baos = null; try { //1.创建服务器端的ServerSocket,指明自己的端口号 ss = new ServerSocket(8889); //2.调用accept()表示接收来自客户端的socket socket = ss.accept(); //3.获取输入流 is = socket.getInputStream(); //4.读取输入流中的数据 baos = new ByteArrayOutputStream(); byte[] buffer = new byte[20]; int len; while((len = is.read(buffer)) != -1){ baos.write(buffer,0,len); } String s = baos.toString(); System.out.println(s); } catch (IOException e) { e.printStackTrace(); }finally { //5.关闭资源 if(is != null){ try { is.close(); baos.close(); } catch (IOException e) { e.printStackTrace(); } } if(socket != null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } }

浙公网安备 33010602011771号