Ann
Ann

Reputation: 703

How can I send and recv from the same socket?

I am going through Beej's guide and I wanted to elaborate on one of the examples, a stream client/server example. In the example the server sends messages, and the client receives.

I would like to make a program that sends AND receives messages. In this case, it would no longer be a server/client architecture, since both the former server and client would perform the same duties. They would be very similar.

In the example the server does the following :

 getaddrinfo(NULL, PORT, &hints, &p);
 sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol));
 bind(sockfd, p->ai_addr, p->ai_addrlen);
 listen(sockfd, BACKLOG);
 new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
 send(new_fd, "Hello, world!", 13, 0);

What do I need to add in order to receive messages as well from the same socket? Is it possible?

I tried many things that didn't work, such as trying to connect() using the original socketfd and using the destinations information. In the end I used two sockets and bind them to the same port with the help of setsockopt(), but I would like to know if there is a better or more efficient method.

Upvotes: 3

Views: 5165

Answers (2)

Alexander Pogrebnyak
Alexander Pogrebnyak

Reputation: 45576

They say "you need two to tango".

Same is true for Client/Server communication (protocol).

Your problems may stem from the fact that the server does not understand that your client has finished sending the data and does not produce the reply.

There are several options to signal the end of communication, here just a few examples:

  • Shut down socket output from the client, this will make the server to sense EOF.
  • Tell the server how many bytes you are sending. Server will read that number, and then after reading that number of bytes will send you a reply.
  • Code some magic byte sequence that signals the End-Of-Request.

Upvotes: 1

Johannes Overmann
Johannes Overmann

Reputation: 5131

You can send and recv from any connected socket.

The direction of the data flow does not have anything to do with the client/server relationship.

It is very common for clients and servers to both send and receive. The pattern they use to send and expect answers is called a protocol (in the sense of an application defined protocol).

Upvotes: 4

Related Questions