Reputation: 703
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
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:
Upvotes: 1
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