Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How exactly does a ServerSocket behave in these scenarios? [closed]

Say we have a ServerSocket and we run accept(). A client connects and a new socket is created with the same local port as ServerSocket. Say the client sends data to this socket. It reaches the port, and reaches the java application. How does the data from here get to the correct socket?

Say two computers are hidden behind the same public IP via NAT. Would that end up creating problems? Would it seem as though the same computer is trying to create a connection (same public ip and same port) I feel as though I am missing something here.

like image 297
nhooyr Avatar asked Nov 24 '25 07:11

nhooyr


1 Answers

A socket connects a local address and port with a remote address and port. This is key: you can accept multiple connections from the same IP as long as the port is different. (For example, you can open the same web page in two different browser tabs since they connect with two different client-side ports.)

The NAT is responsible for making sure that two connections from two separate computers receive a different address/port combination. If they are mapped to the same public IP, the NAT will need to assign a different local port for those connections. As a server, you shouldn't have to worry about this: you simply see two different address/port combinations connecting to your server's address/port, so they're different sockets.

In Java, a ServerSocket acts as an entry point. It binds to your server's address and port, so it's kind of a template for "half of a socket". When a client connects with their address and port, a "full" Socket is created with their half filled in and now the server and client can start talking. Look into how TCP/UDP connections work if that's still not clear enough.

like image 131
Mattias Buelens Avatar answered Nov 25 '25 20:11

Mattias Buelens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!