我正在尝试使用 UDP 在 Java 中实现客户端服务器应用程序。 问题是当客户端连接到服务器时,服务器注册客户端,另一个应用程序尝试使用 clientIP 和 clientPort 连接到客户端; 客户端无法获取任何数据。
我能够重新创建 DatagramSocket 以使用他的 IP 和端口连接到客户端,但是当由不同的应用程序完成此操作时,无法实现通信。
我想提一下,我在服务器上侦听客户端的端口与服务器应用程序正在使用的端口不同。
我们怎样才能实现这种沟通呢?
请帮我。 谢谢。
I am trying to achieve a client server application in Java using UDP. The issue is when client connects to a server, server registers the client and another application tries to use the clientIP and clientPort to connect to the client; client is not able to get any data.
I was able to recreate DatagramSocket to connect to Client using his IP and port but when this done by different application, the communication is not achieved.
I would like to mention the port I am listening to client on server is different than the port which the server application is using.
How can we achieve this communication?
Please help me. Thank you.
发布评论
评论(2)
您的评论“当客户端连接到服务器时..”让我想知道您是否在客户端的 DatagramSocket 上使用了 connect() 。 如果是这样,请勿在套接字上调用 connect()。 UDP 是无连接协议,不需要 connect()。 通过在 UDP 套接字上调用 connect(),套接字只能向 connect() 指定的主机发送/接收数据。
如果情况并非如此,那么我能想到的唯一原因是您的客户端计算机可能启用了某些防火墙,或者您的客户端和服务器或其他主机之间存在 NAT/防火墙。 使用 Wireshark 检查您的客户端是否从其他应用程序接收任何数据包。
希望这可以帮助。
Your comment, "when client connects to a server.." made me wonder if you used connect() on client's DatagramSocket. If so, don't call connect() on the socket. UDP is a connection-less protocol and connect() is not required. By calling connect() on UDP socket, the socket can only send/receive data to/from the host specified with the connect().
If this is not the case, then only reason I can think of is that your client machine may have some firewall enabled, or there's a NAT/Firewall in between your client and the server or other hosts. Check with Wireshark whether your client is receiving any packets from the other app.
Hope this helps.
我可能错过了这一点,但我认为为了让您的客户端能够接受服务器上运行的其他应用程序的连接尝试,您需要在客户端中实现一些侦听模块(接受传入连接的类似服务器的部分)。
您可以在这里找到一些有用的示例: http://www.java2s.com /Code/Java/Network-Protocol/UDP.htm
I maybe miss the point but I think that in order for your client to be able to accept the connection attempts by other application running on your server you need to implement some listening module in your client (server-like part that accept incoming connections).
You can find some usefull examples here: http://www.java2s.com/Code/Java/Network-Protocol/UDP.htm