Java基础知识强化之网络编程笔记05:UDP之多线程实现聊天室案例

1. 通过多线程改进刚才的聊天程序,这样我就可以实现在一个窗口发送和接收数据了

2.  代码示例:文章来源地址:https://www.yii666.com/article/754263.html

(1)SendThread.java,如下:

 package com.himi.udpDemo2;

 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress; public class SendThread implements Runnable { private DatagramSocket ds; public SendThread(DatagramSocket ds) {
this.ds = ds;
} public void run() {
try {
// 封装键盘录入数据
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
String line = null;
while ((line = br.readLine()) != null) {
if ("886".equals(line)) {
break;
} // 创建数据并打包
byte[] bys = line.getBytes();
// DatagramPacket dp = new DatagramPacket(bys, bys.length,
// InetAddress.getByName("192.168.12.92"), 12345);
DatagramPacket dp = new DatagramPacket(bys, bys.length,
InetAddress.getByName("49.123.72.145"), 12306); // 发送数据
ds.send(dp);
} // 释放资源
ds.close();
} catch (IOException e) {
e.printStackTrace();
}
} }

(2)ReceiveThread.java,如下:

 package com.himi.udpDemo2;

 import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket; public class ReceiveThread implements Runnable {
private DatagramSocket ds; public ReceiveThread(DatagramSocket ds) {
this.ds = ds;
} public void run() {
try {
while (true) {
// 创建一个包裹
byte[] bys = new byte[1024];
DatagramPacket dp = new DatagramPacket(bys, bys.length); // 接收数据
ds.receive(dp); // 解析数据
String ip = dp.getAddress().getHostAddress();
String s = new String(dp.getData(), 0, dp.getLength());
System.out.println("from " + ip + " data is : " + s);
}
} catch (IOException e) {
e.printStackTrace();
}
} }

(3)聊天室程序CharRoom.java,调用上面两个线程工具类,代码如下:

 package com.himi.udpDemo2;

 import java.io.IOException;
import java.net.DatagramSocket; /*
* 通过多线程改进刚才的聊天程序,这样我就可以实现在一个窗口发送和接收数据了
*/
public class ChatRoom {
public static void main(String[] args) throws IOException {
DatagramSocket dsSend = new DatagramSocket();
DatagramSocket dsReceive = new DatagramSocket(12306); SendThread st = new SendThread(dsSend);
ReceiveThread rt = new ReceiveThread(dsReceive); Thread t1 = new Thread(st);
Thread t2 = new Thread(rt); t1.start();
t2.start();
}
}

运行效果如下:文章来源地址https://www.yii666.com/article/754263.html文章地址https://www.yii666.com/article/754263.html网址:yii666.com<网址:yii666.com

Java基础知识强化之网络编程笔记05:UDP之多线程实现聊天室案例

版权声明:本文内容来源于网络,版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。文本页已经标记具体来源原文地址,请点击原文查看来源网址,站内文章以及资源内容站长不承诺其正确性,如侵犯了您的权益,请联系站长如有侵权请联系站长,将立刻删除

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信图片_20190322181744_03.jpg

微信扫一扫打赏

请作者喝杯咖啡吧~

支付宝扫一扫领取红包,优惠每天领

二维码1

zhifubaohongbao.png

二维码2

zhifubaohongbao2.png