简体   繁体   English

如何使用Java优先在没有外网IP的两台机器之间建立套接字连接?

[英]How to establish socket connection between two machines with each has no out-net ip preferentially using java?

I'm creating some software which consists of a server and several clients, and I have a requirement that need two clients transfer files with each other. 我正在创建一些由服务器和几个客户端组成的软件,并且我有一个需求,即需要两个客户端相互传输文件。

Its workflow is described below: 其工作流程如下:

  1. A client(file sender) send a request to the server and tells it I need send a file to another client(file receiver). 客户端(文件发送者)向服务器发送请求,并告诉我需要将文件发送到另一个客户端(文件接收者)。
  2. The server returns the ip of file-received client and send a message to file-received client and tell him someone whose ip is .. will send a file to you. 服务器返回文件接收客户端的ip并将消息发送到文件接收客户端,并告诉他ip为..的某人将向您发送文件。
  3. The file sender create a SocketServer and tell server that I'm already ready. 文件发送者创建一个SocketServer并告诉服务器我已经准备好了。
  4. The file receiver create a socket connection connect to file-sender. 文件接收器创建一个套接字连接,连接到文件发送者。
  5. File sender start to send file. 文件发送者开始发送文件。

I've got a problem in step 4: because of the out-net ip, I can't establish socket connections from file receiver to file sender. 我在第4步中遇到问题:由于IP的出网,我无法建立从文件接收者到文件发送者的套接字连接。

Here, out-net ip means that this ip is Router's that the machine connect with. 在这里,外网ip表示此ip是机器连接的路由器。 The machine only have a in-net ip which assigned by Router. 机器只有一个由路由器分配的内网IP。

Some time ago I created a similar application. 前一段时间,我创建了一个类似的应用程序。 If both clients can communicate with the server then why not to use the server as a bridge/gateway. 如果两个客户端都可以与服务器通信,那为什么不将服务器用作网桥/网关。 I mean, the server will sends all transfers file data between both clients. 我的意思是,服务器将在两个客户端之间发送所有传输文件数据。 You don't have to close the original sockets, the one created in step 1 and the one created in step 2 use them to do the transfer between the clients. 您不必关闭原始套接字,在步骤1中创建的套接字和在步骤2中创建的套接字都可以使用它们在客户端之间进行传输。 It's just a matter of a well designed protocol, which, in this case, is not to difficult to implement. 这只是设计合理的协议的问题,在这种情况下,不难实现。

Have you forwarded the appropriate ports on your router? 您是否在路由器上转发了适当的端口? otherwise your connection dies at the router. 否则,您的连接将在路由器上断开。

Your described way brings two problems. 您描述的方式带来两个问题。

Problem 1: In real net world you can find many configurations where file receiver can direct connect two file sender. 问题1:在现实世界中,您可以找到许多配置,文件接收器可以直接连接两个文件发送器。 You have a lot to configure to grant the access. 您需要进行很多配置才能授予访问权限。

Problem 2: You make your code with that design to complicate. 问题2:使用该设计使代码复杂化。 File sender needs to implement a client and a server socket. 文件发送者需要实现客户端和服务器套接字。

IMO a better way would be file sender delivers the desired file to the manager server. IMO更好的方法是文件发送方将所需的文件传递到管理器服务器。 If the file receiver want's the file he download it simply from the server. 如果文件接收者想要该文件,则只需从服务器下载即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM