我试图发回一个数据包给用户,通知他们当前在服务器上的所有人,当他们发送一条消息到服务器上有“who”这个词的时候。UDP在这里丢失了我的数据包的一部分吗?
这里是我的代码:
else if(response.contains("who"))
{
System.out.println("Size of names collection: "+names.size());
buf = null;
buf = names.toString().getBytes();
int thisPort = packet.getPort();
packet = new DatagramPacket(buf, buf.length,packet.getAddress(),thisPort);
socket.send(packet);
}
上面打印语句的输出是2,表明有两个人,例如安德鲁和詹姆斯。现在,当我打包并发送它,我会期待它输出这样的:
[安德鲁,詹姆斯]
但不是客户端获取:
[安德鲁,
并且那它。有什么问题? BTW我不得不使用UDP,这和不能切换到TCP
UPDATE
下面是客户端类中接收的数据包的代码:
while(true)
{
try
{
// Set the buf to 256 to receive data back from same address and port
buf = null;
buf = new byte[256];
packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.receive(packet);
String response = new String(packet.getData());
// Receive the packet back
System.out.println(response);
}
catch(IOException e)
{
}
}
我想你刚刚发布了一半你的问题 – Chirlo 2012-04-18 18:04:35
所以任何想法的人? – Katana24 2012-04-18 18:53:52
你是说这种事情总是发生,或者只是偶尔和随意地发生? – 2012-04-18 18:57:45