views:

121

answers:

1

I'm writing a chat program and for the server, when I send data can the send() function take a long time to send out the data?

Here is my problem: I'm using linux 2.6 with epoll, server in single thread If send() blocks, then this means all other activity on the server will stop. Like if there is a very slow client that does not send ACK responses for a long time to a tcp packet, will the send function just move on right away, or will it wait a long time for the client. The thing I don't want is for a single/few slow clients to cause delays in the chat server.

What I want is for send() to nonblock and to return very quickly. If it doesn't send all the data, it will simply return the amount sent and I will remove that from the buffer and keep sending next time serviced until all data sent. Basically I don't want send to block for a long time on a slow or unresponsive client.

+2  A: 

You can set a socket to non-blocking mode and a send will not block. The problem is that you'll have to manage the fact that a partial write occurred and send the rest of the data when the write file descriptor becomes active again.

In general I've found that doing both send and recv in non-blocking mode, while complicating the program, works pretty well.

Use something like:

    if (-1 == (flags = fcntl(fd, F_GETFL, 0)))
        flags = 0;
    return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
Richard Pennington