10.UDP实现聊天
循环发送消息:
1 package com.Inet.chat; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.net.DatagramPacket; 7 import java.net.DatagramSocket; 8 import java.net.InetSocketAddress; 9 10 public class UdpSenderDemo01 { 11 public static void main(String[] args) throws IOException { 12 DatagramSocket socket = new DatagramSocket(8888); 13 14 //准备数据:控制台读取 System.in 15 16 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 17 while (true) { 18 String data = reader.readLine(); 19 byte[] datas = data.getBytes(); 20 DatagramPacket packet = new DatagramPacket(datas, 0, data.length(), new InetSocketAddress("localhost", 6666)); 21 22 socket.send(packet); 23 if (data.equals("bye")) { 24 break; 25 } 26 } 27 socket.close(); 28 } 29 }
循环接收消息:
1 package com.Inet.chat; 2 3 import java.net.DatagramPacket; 4 import java.net.DatagramSocket; 5 6 public class UdpReceiveDemo01 { 7 public static void main(String[] args) throws Exception { 8 DatagramSocket socket = new DatagramSocket(6666); 9 10 while (true) { 11 12 //准备接收包裹 13 byte[] container = new byte[1024]; 14 DatagramPacket packet = new DatagramPacket(container, 0, container.length); 15 socket.receive(packet); 16 17 //断开连接 18 byte[] data = packet.getData(); 19 String receiveData = new String(data, 0, data.length); 20 21 System.out.println(receiveData); 22 23 if (receiveData.equals("bye")) { 24 break; 25 } 26 } 27 socket.close(); 28 } 29 } 30 31 //开启接收端,再开启发送端,结果: 32 发送端发送消息,接收端接收对应的消息