Java如何使用UDP协议实现多人聊天?

我的代码,有问题,不能实现....逻辑线程:publicclassLogicThreadextendsThread{privateDatagramPacketreceiv... 我的代码,有问题,不能实现....

逻辑线程:
public class LogicThread extends Thread {

private DatagramPacket receive;
private boolean bool; //标识是否已经在服务器接收过数据

public LogicThread(DatagramPacket receive){
this.receive = receive;
bool = true;
}

@Override
public void run() {
DatagramSocket server = null;
try {
server = new DatagramSocket();
while(true){
//接收
if (!bool) {
byte[] b = new byte[1024];
DatagramPacket receive = new DatagramPacket(b,b.length);
server.receive(receive);
}
byte[] r = receive.getData();
InetAddress inet = receive.getAddress();
String msg = new String(r,0,receive.getLength());
System.out.println(inet+"客户端:"+msg);
if ("bye".equals(msg)) {
System.out.println("服务器关闭....");
break;
}
//发送
System.out.print("输入信息:");
String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
byte[] s = str.getBytes();
DatagramPacket send = new DatagramPacket(s,s.length,inet,receive.getPort());
server.send(send);
bool = false;

服务器:
DatagramSocket server = new DatagramSocket(10000);
System.out.println("*****服务器启动*****");
while(true){
//接收
byte[] b = new byte[1024];
DatagramPacket receive = new DatagramPacket(b,b.length);
server.receive(receive);
count++;
System.out.println("第"+count+"个客户端连接。");
LogicThread lt = new LogicThread(receive);
lt.start();

客户端省略....
展开
 我来答
匿名用户
2013-10-12
展开全部
UDP 是广播的,如果是做实时的聊天,就开两个线程、不需要服务器端。一个专门接收、一个做发送
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式