如何让多个(UDP)客户端仅接收来自特定服务器的数据包?

时间:2014-07-15 02:36:50

标签: java sockets udp client-server client

我正在创建一个接口,其中多个客户端定期向服务器发送更新(存储其所有地址),然后服务器将包含所有客户端更新的数据包发送到所有客户端。它看起来一切正常,但是当我一起运行服务器和客户端时,我收到了这个错误:

Exception in thread "main" java.net.BindException: Can't assign requested address
at java.net.PlainDatagramSocketImpl.bind0(Native Method)
at java.net.AbstractPlainDatagramSocketImpl.bind(AbstractPlainDatagramSocketImpl.java:95)
at java.net.DatagramSocket.bind(DatagramSocket.java:376)
at cygnus.client.CygnusClient.main(CygnusClient.java:51)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)

它所说的话是(在客户端):

socket = new DatagramSocket(null);
InetSocketAddress address = new InetSocketAddress("server.ip.address", 7777);
socket.bind(address);

服务器打开套接字如下:

socket = new DatagramSocket(9999);

注意:我在与客户端相同的网络上运行服务器,这是我猜测错误的来源。不幸的是,我希望能够在同一台计算机上运行服务器和客户端(并在其他计算机上安装其他客户端),尤其是出于测试目的。

如何确保客户端只侦听来自我的服务器端口的数据包?有更好的方法吗?

P.S。如果我需要包含更多代码来帮助回答这个问题,请告诉我,我很乐意,我只是不知道我需要包含什么。

2 个答案:

答案 0 :(得分:0)

UDP客户端不应该监听端口。它只是将一个DatagramPacket发送到UDP服务器并接收响应。用于客户端套接字的端口由os。

管理
// any free port will be assigned by os
DatagramSocket clientSocket = new DatagramSocket(); 
// create a packet to be sent ot server
DatagramPacket requestPacket = new DatagramPacket(outBuf, outBuf.length, serverAddress, 9999);
// sending the packet to udp server 
clientSocket.send(requestPacket); 

DatagramPacket responsePacket = new DatagramPacket(inBuf, inBuf.length)
// client will be blocked until a response is sent by server
clientSocket.receive(responsePacket); 

在服务器端

 DatagramSocket socket = new DatagramSocket(9999); 
 DatagramPacket requestPacket = new DatagramPacket(inBuf, inBuf.length);
 // will be blocked until a request is received by the server
 socket.receive(requestPacket); 
 // the client's port and ip address will be populated in the packet on receiving a request.
 DatagramPacket responsePacket = new DatagramPacket(outBuf, outBuf.length, requestPacket.getAddress(), requestPacket.getPort());
 // the data will be sent to the client.
 socket.send(responsePacket);

答案 1 :(得分:0)

  

如何确保客户端只侦听来自我的服务器端口的数据包?

只有connect()客户端套接字到该IP:端口。然后他们不会从其他任何人那里收到。