1. 通过多线程改进刚才的聊天程序,这样我就可以实现在一个窗口发送和接收数据了
2. 代码示例:
(1)SendThread.java,如下:
1 package com.himi.udpDemo2; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import .DatagramPacket; 7 import .DatagramSocket; 8 import .InetAddress; 9 10 public class SendThread implements Runnable {11 12private DatagramSocket ds;13 14public SendThread(DatagramSocket ds) {15 this.ds = ds;16}17 18public void run() {19 try {20 // 封装键盘录入数据21 BufferedReader br = new BufferedReader(new InputStreamReader(22 System.in));23 String line = null;24 while ((line = br.readLine()) != null) {25 if ("886".equals(line)) {26 break;27 }28 29 // 创建数据并打包30 byte[] bys = line.getBytes();31 // DatagramPacket dp = new DatagramPacket(bys, bys.length,32 // InetAddress.getByName("192.168.12.92"), 12345);33 DatagramPacket dp = new DatagramPacket(bys, bys.length,34InetAddress.getByName("49.123.72.145"), 12306);35 36 // 发送数据37 ds.send(dp);38 }39 40 // 释放资源41 ds.close();42 } catch (IOException e) {43 e.printStackTrace();44 }45}46 47 }
(2)ReceiveThread.java,如下:
1 package com.himi.udpDemo2; 2 3 import java.io.IOException; 4 import .DatagramPacket; 5 import .DatagramSocket; 6 7 public class ReceiveThread implements Runnable { 8private DatagramSocket ds; 9 10public ReceiveThread(DatagramSocket ds) {11 this.ds = ds;12}13 14public void run() {15 try {16 while (true) {17 // 创建一个包裹18 byte[] bys = new byte[1024];19 DatagramPacket dp = new DatagramPacket(bys, bys.length);20 21 // 接收数据22 ds.receive(dp);23 24 // 解析数据25 String ip = dp.getAddress().getHostAddress();26 String s = new String(dp.getData(), 0, dp.getLength());27 System.out.println("from " + ip + " data is : " + s);28 }29 } catch (IOException e) {30 e.printStackTrace();31 }32}33 34 }
(3)聊天室程序CharRoom.java,调用上面两个线程工具类,代码如下:
1 package com.himi.udpDemo2; 2 3 import java.io.IOException; 4 import .DatagramSocket; 5 6 /* 7 * 通过多线程改进刚才的聊天程序,这样我就可以实现在一个窗口发送和接收数据了 8 */ 9 public class ChatRoom {10public static void main(String[] args) throws IOException {11 DatagramSocket dsSend = new DatagramSocket();12 DatagramSocket dsReceive = new DatagramSocket(12306);13 14 SendThread st = new SendThread(dsSend);15 ReceiveThread rt = new ReceiveThread(dsReceive);16 17 Thread t1 = new Thread(st);18 Thread t2 = new Thread(rt);19 20 t1.start();21 t2.start();22}23 }
运行效果如下: