Search code examples
csocketsunixtcpposix-select

C: Using select() to write to new client


I'm creating a chat server/client using C and I'm using select() to monitor my sockets.

The program is separated into 3 parts, the server, the viewing client. and the submitting client. The submitting client connects a socket to the server and when there is text to be read from the client, select triggers that it needs to be read. If it's a new client connection, select will also trigger so that I can accept the connection and assign a socket to the client.

My issue is with the viewing client which is supposed to trigger select when it is writable. However, when there is a new connection, select doesn't do anything.This source claims that select will only be triggered on write-fd if they have already been connected. However, how can I connect a new writing client?

server:

if (select(128, &read_fds, &write_fds, NULL, NULL) == -1){
    ...
}

if (FD_ISSET(viewing_socket, &write_fds)){
    printf("%d is a new observer connection\n", viewing_socket);
    new_observer_connection();
}
if (FD_ISSET(submitting_socket, &read_fds)){
    printf("%d is a new participant connection\n", submitting_socket);
    new_participant_connection();
}

So when a new submitting client connect, it accepts the connection and adds that new socket to &read_fds to monitor for reads. However, new viewing client connections don't seem to trigger a thing.


Solution

  • Seconds after posting this I found the solution. The listening sockets both need to be read from when there is a new client. Only after accepting the connection does the new socket get watched for writing. The socket listening for new connections obviously needs to be read from not written to. Will keep this up for others...