public class UdpSendDemo {
public static void main(String[] args) throws Exception{
DatagramSocket datagramSocket = new DatagramSocket(888);
while (true){
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String read = reader.readLine();
byte[] data = read.getBytes();
DatagramPacket packet = new DatagramPacket(data,0,data.length,new InetSocketAddress("localhost",666));
datagramSocket.send(packet);
if (read.equals("退出")){break;}
}
datagramSocket.close();
}
}
public class UdpReceiveDemo {
public static void main(String[] args) throws Exception{
DatagramSocket socket = new DatagramSocket(666);
while (true){
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);
socket.receive(packet);
byte[] data = packet.getData();
String data0 = new String(data,0,data.length);
System.out.println(data0);
if (data0.equals("退出")){
break;}
}
socket.close();
}}
|