2
votes

I found this defeinitons of funcion listen and recv in winsock library (TCP/IP stream communication).

The listen function places a socket in a state in which it is listening for an incoming connection.

The recv function receives data from a connected socket or a bound connectionless socket.

Does it mean that if I want to receive data from particular socket I should firstly use listen and then recv? I'm not sure if I understand this correctly.

1
You're correct. First use listen and then recv. Listen "listens" for other computers, and recv "recieves" data. - Greg M
And one more question. So can I use listen instead of connect? - Agnieszka Mikołajczyk
connect is for clients trying to connect to a server, and listen is for servers listeneing for a client. If you're making a server you shouldn't use connect, and vice versa. - Greg M
You'd use listen for the server and connect for the client. - Moustafa Elqabbany
Thank you, now everythink is clear - Agnieszka Mikołajczyk

1 Answers

3
votes

The functions listen and recv have quite different functionalities and uses.

The listen function is designed to allow a server awaiting the connection of one or more clients to listen on a port for if anyone connects.

The recv function is used on an already established socket to receive data which has been sent from the machine at the other end of that socket.

As it has been mentioned in comments, I shall also mention connect. Connect is the counterpart of listen. It talks to the port which a listening machine is listening on and establishes a socket with that machine.

what the BSD socket and winsock libraries don't really make clear is that from a programmers perspective there are two quite different kinds of socket, a listening socket and an established one.

A server will first need to create a listen socket with which it waits for clients, this socket is not used for actually sending any data, it only exists in order to aid the creation of an established socket. However the listening socket does not become the established socket, when a client connects, the listen socket actually creates a second socket for the data transfer.

The established socket is the kind we recognise and use for most things. It is a socket with machines at both ends, listening and sending to perform data transfer.