views:

28

answers:

1

I'm building a server that serves two clients using streamreaders/writers (using networkstreams), using newline symbols to indicate the start/end of a new command. Because readline (and writeline too, but that's not an issue), will block until there actually is a line to read, I use socket.select in order to determine when there is a line to read. However, because I don't know how many lines there are to read, I just read one, and loop back using socket.select again. Which, according to the documentation: http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.select.aspx says that if it's still readable, it will make the list to the readable sockets and continue, or if you've read everything, it won't. Here is my code:

DateTime startTime = DateTime.Now;
DateTime endTime = startTime.AddSeconds(Double.Parse(playTime));
List<Socket> clients;
double secondsLeft;
while ((secondsLeft = (endTime - DateTime.Now).TotalSeconds) > 0)
{
    clientSockets = new List<Socket>() { clientSocket1, clientSocket2 };
    Socket.Select(clientSockets, null, null, (int)(secondsLeft * 1000000));
    if (clientSockets.Contains(clientSocket1))
    {
        handlePlayer(reader1, writer1, writer2);
    }
    if (clientSockets.Contains(clientSocket2))
    {
        handlePlayer(reader2, writer2, writer1);
    }
}

However, in a unit test, when the clients send a lot of words in rapid succession, it will only read the first word (from each player) and then scoekts.select will freeze until the timout is reached. So is this the right way to see if there's more data in the network stream? (As a streamreader).

A: 

Why on earth use Socket.Select here? we are not on BSD Unix any more.

Use async I/O via Socket.BeginReceive or similar to handle both streams concurrently in an event-driven way.

If you really want to use streams I imagine StreamReader.EndofStream could be useful here.

Steve Townsend