网络编程(java.net)
一、网络要素
1、IP地址:InetAddress
192.168.1.255(192.168.1网段的广播地址)
2、端口号
0--65535
0-1024
3、传输协议
UDP
将数据及源和目的封装成数据包中,不需要建立连接
数据包大小限制在64K内
因无连接,不可靠协议
不需要建立连接,速度快
TCP
建立连接,形成传输数据的通道
在连接中进行大数据量传输
通过三次握手完成连接,是可靠协议
必须建立连接,效率稍低
二、UDP协议实例
网络通信:发送端
1 public class UDPSendDemo { 2 3 /** 4 * @param args 5 * @throws IOException 6 */ 7 public static void main(String[] args) throws IOException { 8 /* 9 * 创建UDP传输的发送端 思路: 10 * 1、建立udp的socket服务 11 * 2、将发送的数据封装到数据包中 12 * 3、通过udp的socket服务将数据包发送出去 13 * 4、关闭socket服务 14 */ 15 // 1、 16 DatagramSocket ds = new DatagramSocket(); 17 // 2、 18 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 19 String line=null; 20 while ((line=br.readLine())!=null) { 21 byte[] buff = line.getBytes(); 22 DatagramPacket dp = new DatagramPacket(buff, buff.length, InetAddress.getByName("172.28.188.168"), 10000); 23 ds.send(dp); 24 } 25 26 ds.close(); 27 28 } 29 30 }