- 网络三要素:IP地址:即设备在网络中地址,是唯一标识 ,端口:即应用程序在设备中的唯一标识 , 协议:即数据在网络中传输的规则 ,常见协议:UDP、TCP协议
- 常见命令:ipconfig 查看本机地址 ping+ip地址: 检查网络是否连通
- 127.0.0.1 可以代替本机ip地址,常用与测试 端口取值范围:1024–65535
- UDP:面向无连接协议,传输速度快、但不安全,数据容易丢失
- TCP:面向连接协议,传输慢 ,上传无限制大小,数据安全
public class sendingend {
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket();
String s = "udp协议演示";
byte[] bytes = s.getBytes();
InetAddress byName = InetAddress.getByName("127.0.0.1");
int port = 10000;
DatagramPacket datagramPacket = new DatagramPacket(bytes,bytes.length,byName,port);
datagramSocket.send(datagramPacket);
datagramSocket.close();
}
}
public class receivingend {
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket(10000);
byte[] bytes = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(bytes,bytes.length);
System.out.println("-------接受前-------");
datagramSocket.receive(datagramPacket);
System.out.println("-------接受后-------");
byte[] data = datagramPacket.getData();
int length = datagramPacket.getLength();
System.out.println(length);
System.out.println(new String(data));
datagramSocket.close();
}
}
|