咨询
发送方
package Chat;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class UdpSendDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(8888);
//准备数据,控制台读取数据 system.in
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 6666));
socket.send(packet);
if (data.equals("bye")){
break;
}
}
socket.close();
}
}
接收方
package Chat;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpReceiverDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(6666);
while (true){
byte[] container = new byte[10];
DatagramPacket packet = new DatagramPacket(container,0,container.length);
socket.receive(packet);
byte[] data =packet.getData();
String receivedata = new String(data, 0, data.length);
System.out.println(receivedata);
if (receivedata.equals("bye")){
break;
}
}
socket.close();
}
}
标签:DatagramSocket,12,20,java,2022,import,new,net,data From: https://www.cnblogs.com/RUI2022/p/16994365.html