I want to make a multi client - one server quiz application. In this, firstly, the clients will connect to the server and will registered themselves. Then, the server will multicast a question to every client, who have registered themselves to the server. The clients will then respond with the answer, which will be send only to the server. And then server will send the the score of each client to the respective client.
This is what I am trying to do in the above application-
1. As I have too multicast
, thats why I am Making my server socket asSOCK_DGRAM
(i.e.,UDP). Then I am using CLASS-D
ip address, for making a group( to which server will multicast). Then is using setsockopt
, I am adding the clients to this group, so that they can recieve the question.
2.As I want to listen the answers from all the clients, so I was thinking of using select
. It uses the socket descriptor to select between various clients, as to know which is ready for reading.
But the problem is, when I am using SOCK_DGRAM socket, it doesnot perform listen
and accept
functionality. So, I will not get a socket descriptor(which is returned by accept
). Thats why, I will not be able to use select
(as it uses only file descriptors).
So, how am I to proceed, as I want to use UDP functionality - MULTICASTING, as well as TCP functionality - a socket descriptor for each connection.
3 Answers
Even when using UDP and unconnected sockets, you can still use functions like select
. Simply bind the server socket to an address, and use that socket for select
. When the socket is readable a client has sent something with e.g. sendto
and you can do e.g. recvfrom
.
However, I would really recommend you to use TCP sockets, it will make many things simpler, especially when it comes to the communication protocol (remember that UDP packages can be lost or come out of order, you have to handle that yourself).
As you said, select
is not usefull here since you only have one socket on the server side.
This socket is used to send datagrams with sendto
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen);
in dest_addr
you specify the destination address for the datagram.
Using recvfrom(2)
on a UDP socket is similar :
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen);
src_addr
is the sender address, so you are able to identify the client which has sent the response.
recvfrom
calls are blocking until data are available for reading (unless you set the socket to unblocking).
You could just loop to receive all the responses.
select
problem, you can listen on UDP sockets, and useconnect
on the clients andaccept
in the server without problems, just like for TCP. – Some programmer dude