UDP
发送端
- 获取接收端的地址
- 造一个包
- 发送数据
- 关闭资源
public class UdpClientDemo {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
int port = 9090;
String str = "你好啊!服务器";
DatagramPacket datagramPacket = new DatagramPacket(str.getBytes(), 0, str.getBytes().length, inetAddress, port);
socket.send(datagramPacket);
socket.close();
}
}
接收端
- 打开自己的端口
- 造一个包用来接收数据
- 接收数据
- 关闭资源
public class UdpServerDemo {
public static void main(String[] args) throws Exception{
DatagramSocket socket = new DatagramSocket(9090);
byte[] buffer = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(buffer,0,buffer.length);
socket.receive(datagramPacket);
System.out.println(datagramPacket.getAddress());
System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));
socket.close();
}
}
|