I have the following basic server/client java code, that works when server and client are in the same network:-
Connected via the same router.
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
Questions (may be naive and basic):
Is there a way to do this without port forwarding and using Java?
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.
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?
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!