0

I have the following basic server/client java code, that works when server and client are in the same network:-

  1. Connected via the same router.

  2. Client directly connected to Server over Wifi.

The use case desired: Client knows Server IP/Port (which may be local or anywhere over the internet). Client sends byte array to Server (which is listening to the port). Server processes the received byte array.

Here's the code (only relevant snippet, omitted try-catch blocks here):

Server.java

public static final int SERVERPORT = 4444;
byte[] inBuffer = new byte[1024];
int bytes

ServerSocket serverSocket = new ServerSocket(SERVERPORT);
Socket client = serverSocket.accept();
InputStream inputStream = client.getInputStream();

bytes = inputStream.read(inBuffer);

/* now process input */

Client.java

OutputStream tmpOut;


/* Server IP and PORT are known to the client, manually entered by user */
InetAddress serverAddress = InetAddress.getByName(ServerIP);
serverSocket = new Socket(serverAddress,SERVERPORT);
tmpOut = serverSocket.getOutputStream();
tmpOut.write(buffer);

This works when server is in same network as client, as expected. If I however, connect server to a different network, and client to another network, and then run the above client code, using the Public IP of the server, it does not connect to the server.

These previous questions suggest that the client-side router can't find the server, and the server needs to forward it's port:

Socket Listener to non-local IP

Non-local connection with sockets

Socket server on WAN

Questions (may be naive and basic):

  1. Is there a way to do this without port forwarding and using Java?

  2. If port forwarding is necessary, how do I forward application port from inside the server code. My user will be installing the server code on his/her machine, and I wouldn't trouble the user to manually forward the port.

  3. How does a known server like Google or Stackoverflow listen to incoming streams from random clients. How are these servers different (by concept) from the above server code I have posted?

  4. Do I need to implement my server as a public web server, just to receive a byte array?

If not code, conceptual insights appreciated. Thanks!

4

1 回答 1

0

当我通过 Java 搜索 NAT 时,在 SO 上找到了以下答案:

通过 NAT 的套接字

以上导致我打孔。我在这个问题的答案中找到了更多关于打孔和防火墙、NAT 的概念信息:

打孔和 NAT

基于上述讨论的更多资源:

跨 NAT 的 P2P

这些资源帮助我完全理解了这个概念。完成后,我将在 java 中发布我的代码。

感谢 paulsm4

于 2013-01-03T20:17:46.117 回答