I don't understand TCP sockets

Advertisements

I’m writing a simple TCP client and server socket program in C.

What I don’t understand is this:
On my client code, it seems having a single socket for both receiving and sending is fine.

But on my server code, I need to have two sockets:
a socket for accepting the connection, and a different one for sending packets to the client.

I don’t understand how this makes sense. If I can both SEND and RECEIVE on side A using a single socket, why can’t I do the same on side B?

>Solution :

A socket represents a pair of endpoints. Data sent from one endpoint is received by the other endpoint.

For a TCP client, 1 socket is enough, as it uniquely represents the connection between the local ip/port which the client is bound to, and the remote server ip/port which the client is connected to. Which is why you can use 1 socket for both sending and receiving application data.

For a TCP server, 1 sockets is not enough. The listening socket represents only the local ip/port that the server accepts clients on, but there is no remote client connected to this socket, so that endpoint is always empty. You can’t send or receive application data on this socket. accept() returns a new socket that represents the connection between the server’s local ip/port which the client was accepted on, and the remote ip/port where that client connected from. Also, think about when there are multiple clients connected to the server at the same time. Each connection has to be uniquely represented. You can’t do that with just 1 pair of endpoints on 1 listening socket, hence the need for a new socket per accepted connection.

Leave a ReplyCancel reply