Reputation: 1798
I take this tutorial for server socket programming link. For the functionality, I have no problem about that, and what I'm asking is more about architecture design question. Please take a look in the tutorial. We actually see two file descriptors, one when calling socket()
, and one when calling accept()
. It makes sense why we get a file descriptor when creating a socket because we treat a socket as a file; it also makes sense that we have to have multiple file descriptors when accepting different connections. But why do we need to have both to make it work?
Upvotes: 6
Views: 3897
Reputation: 198324
Imagine a quick repair shop, where customers bring their PCs to be repaired, then sit in the waiting room till the PC is fixed. Not the long repairs that take weeks; the quick repairs that take an hour.
The sane way to run this shop is to have a receptionist who listens to the customers, takes the broken PC and passes it on to whichever repairman is currently free. He accepts the job, and goes off to work. The customer goes and sits. As another customer arrives, the receptionist is free to greet them, and directs them to another repairman if one is available.
The not sane way to run this shop is to have a receptionist who repairs the PC by themselves. The next customer to come to the shop has to hold their broken PC in their arms, waiting for the receptionist to repair the PC of the previous customer before they can hand over their load. Eventually, people's hands get tired, and they leave the queue, possibly to find a saner shop. Meanwhile, the poor receptionist is stressed, looking at all the people waiting to interact with her...
Upvotes: 3
Reputation: 7842
Ideally, they are two different TCP endpoints, where one is used as listening endpoint(LISTENING) and the other one as the accepted incoming connection (ESTABLISTED). You can close the listening endpoint once you are done with accepting connections.
Upvotes: 1
Reputation: 13796
The 1st socket is called the listening socket. TCP is a connection oriented stream. Each client connection operates on its own socket just like a file. If you only have one socket, you will not be able to distinguish which connection the data received on it belongs to. So the way TCP socket designed is to have the listening socket operate in LISTEN
mode, and each time a client want to establish connection to the server, the accept
call will return a new socket, aka the client socket, to represent the new connection, so that it is used to communication with this client exclusively.
On the other hand, UDP is a connectionless datagram-based protocol, in which just one socket is used to handle all data from all clients.
Upvotes: 6
Reputation: 182769
One socket represents the listening endpoint. The other socket represents the accepted incoming connection. If you don't want to accept any more connections, you can close the listening socket after calling accept
.
Upvotes: 5