发送端
package com.g.udp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import sun.net.InetAddressCachePolicy;
public class Send {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
DatagramSocket socket = new DatagramSocket(9999);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String readLine = reader.readLine();
byte[] bytes = readLine.getBytes();
DatagramPacket packet = new DatagramPacket(bytes,0, bytes.length,new InetSocketAddress("localhost",6666));
socket.send(packet);
if (bytes.equals("bye")) {
break;
}
}
socket.close();
}
}
**接收端**
package com.g.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Accipt {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
DatagramSocket socket = new DatagramSocket(6666);
byte[] bt = new byte[1024];
while (true) {
DatagramPacket packet = new DatagramPacket(bt, 0, bt.length);
socket.receive(packet);
byte[] data = packet.getData();
String string = new String(data,0,data.length);
System.out.println(string);
if (string.equals("bye")) {
break;
}
}
socket.close();
}
}
发送内容
1 2 3 11 22 2 1 11111111111111111 22222 你好 啊啊啊啊啊啊啊啊啊
接收内容
![在这里插入图片描述](https://img-blog.csdnimg.cn/f8fa13fea34d432583c13a29bde3efa9.png)
会覆盖
|