Search code examples
javasocketsnetwork-programmingserversocket

What happens when data is written to socket.getOutputStream on server side?


I have a doubt on ServerSocket Client: android Server: my pc with static IP I'm using a socket on client's side to connect to server, server accepts the socket and get's it's input and output streams. The thing is when server writes data to that outputstream i can't understand how client receives the message(i know how to). If it's the case that server sends data to client,how can it be possible considering the client(android) doesn't have an ip which could be accessed over internet. I'm aware of long polling and is that the method used here too?


Solution

  • Let me try to answer the question how a server can send any data to a client, when that client does not have a public internet address.

    The technique to do this is called Network address translation (NAT).

    The client creates a socket and uses that socket to send a request to the server. This request is first sent to the Internet Gateway of the client and addressed to the server.

    The Internet Gateway is usually a router that does have a public IP address. This router will remember that the client has sent data to the server and will replace the IP and Port in the from field in the data with the IP of the router.

    Now the data packet reaches the server and when the server decides to send an answer it will address it to the routers IP and Port.

    When the packet reaches the router it looks up what local client is associated with that port and then rewrites the Port and IP in the packet to match the local client.

    Then it sends the packet to the client.