UDP实现循环接收输入
UDP实现循环接收输入
发送端:
package com.example.network;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class ChatSenderDemo01 {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(6666);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String msg = reader.readLine();
byte[] dataBytes = msg.getBytes();
DatagramPacket packet = new DatagramPacket(dataBytes, 0, dataBytes.length, new InetSocketAddress("localhost", 8888));
socket.send(packet);
if (msg.equals("bye")) {
break;
}
}
reader.close();
socket.close();
}
}
接收端:
package com.example.network;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class ChatReceiverDemo02 {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(8888);
while (true) {
byte[] msg = new byte[1024];
DatagramPacket packet = new DatagramPacket(msg, 0, msg.length);
socket.receive(packet);
String data = new String(packet.getData(), 0, packet.getLength());
System.out.println(data);
if (data.equals("bye")) {
break;
}
}
socket.close();
}
}