[Mono-list] Socket.Select problem

RoBiK robik@mailbox.sk
Tue, 4 May 2004 10:57:08 +0200


It seems to me, that you don't fully understand the concept of select/poll.
The behavior that you describe is correct fo select & poll.
For your app, you should use poll, because you are working with single
socket. Use select only if you need to work with multiple socket

Try this:

		public string GetMessage(int timeOut, Socket socket)
			string s = string.Empty;
			while(socket.Poll(timeOut, SelectMode.SelectRead))
				byte[] buffer = new byte[1];
				int count = socket.Receive(buffer, 1,
				if(count == 0)
					//connection closed
					return string.Empty;
					char c = (char)buffer[0];
					if(c == '\n')
						//end of line received
						return s;
					s += c;
			return string.Empty;

Here is the MSDN documentation for Socket.Poll:


-----Original Message-----
From: Dennis Jarosch [mailto:ya_luva@uni.de] 
Sent: Montag, 03. Mai 2004 22:37
To: mono-list@ximian.com
Subject: [Mono-list] Socket.Select problem


This is probably not mono-devel related but I'd really appreciate it, if
somebody could help.

I am writing a client application (w/ mono and C#) that communicates with
the server via message-strings. These strings are terminated by the usual
'\n'. The '\n' may be followed by additional data, which is why the string
has to be processed before reading the rest.

I am currently getting one character at a time, checking the socket-state
with Socket.Select. Yes, using a buffer would be nice, but the
server-protocol forces me to do it this way. ;-)

Somehow Select (and Poll, which I have also tried) does not seem to work
correctly. Sometimes I get correct results, mostly nothing is read though.
When using a buffer, everything works rather fine. When using -1 as timeout
value, everything works fine but blocks after the last char.

This is my code:
++++++++++++++++++++++++ Select

ArrayList listenList = new ArrayList();

int count = 0;
bool read = true;

while (read)
	read = false;
	Socket.Select(listenList, null, null, 5000);
	if (listenList.Contains(socket))
		read = true;
		count = socket.Receive(buffer, 1, SocketFlags.None);

		Console.WriteLine("count: " + count);

		message += (char)buffer[0];
		if ((char)buffer[0] == '\n')
			return message;

++++++++++++++++++++++++ Poll

while (socket.Poll(-1, SelectMode.SelectRead)) {
	count = socket.Receive(buffer, 1, SocketFlags.None);

	message += (char)buffer[0];
	if ((char)buffer[0] == '\n')
		return message;	


Thanks for reading!

Mono-list maillist  -  Mono-list@lists.ximian.com