我使用UDP创建客户端 - 服务器应用程序。在有人问我为什么使用UDP而不是TCP之前让我通过声明它用于分配来告诉答案。好的问题!
我创建了一个客户端类,它生成一个线程以便将数据包发送到UDP服务器。主线程侦听进入的数据包。服务器类充当欢迎消息推送服务以及中间人将客户端的消息传递给每个人。
当我创建两个客户端时,第一个客户端输出如下:
Please enter your name for the server:
James
Welcome to the server James
Hi all // User james types this
James: Hi all // Outputs his message to him once - that's fine
Hi mate // Output from another user
这就是我希望所有客户端发送和接收消息的方式。但是当第二个客户端执行相同操作时,我得到以下输出:
Please enter your name for the server:
Owen
Welcome to the server Owen
Hi all // Client one (James wrote this)
Hi mate
Owen: Hi mate
Hi mate
请注意,我已在此处两次收到相同的消息,但在第一个客户端上我只收到一次。这是我在服务器类中用于向客户端发送消息的逻辑:
// Get the response
String response = new String(packet.getData());
// Test - send a message from the server to each user
if( ports.size() > 1 )
{
for( int i = 0; i < ports.size(); i++ )
{
System.out.println( "Values in port arraylist: "+ports );
if( packet.getPort() == ports.get(i) )
{
} else
{
// String toSend = names.get(i).concat( ": "+response );
// System.out.println( toSend );
buf = response.getBytes();
System.out.println( "Packet Receieved from Port: "+packet.getPort()+"\nPorts.get: "+ports.get(i) );
// Could store all address in own arraylist for outside local host networking
int thisPort = ports.get(i);
packet = new DatagramPacket( buf, buf.length,packet.getAddress(),thisPort );
socket.send(packet);
System.out.println( "Sending message to port "+ports.get(i) );
}
}
System.out.println( "\n" );
packet = null;
}
为了测试这个,我添加了一些输出行来看看这里发生了什么并得到了这个:
Values in port arraylist: [61493, 61494]
Values in port arraylist: [61493, 61494]
Packet Receieved from Port: 61493
Ports.get: 61494
Sending message to port 61494
Values in port arraylist: [61493, 61494]
Packet Receieved from Port: 61494
Ports.get: 61493
Sending message to port 61493
Values in port arraylist: [61493, 61494]
Packet Receieved from Port: 61493
Ports.get: 61494
Sending message to port 61494
答案 0 :(得分:0)
我不知道为什么会这样做但是我通过在代码中放置一个全局变量来保存端口的临时值以进行比较来修复它:/