I'm building a server application which accepts socket connections and
I ran into some problems.
The socket is asynchronous and therefore uses the BeginXXX and EndXXX
methods in the Socket class to receive data. I also use a
ManualResetEven t to signal the main thread when data arrives.
Here is the code I'm running:
using System;
using System.Net;
using System.Net.Sock ets;
using System.Threadin g;
using System.Text;
namespace SocketClient
public class StateObject
public Socket workSocket = null;
public const int BufferSize = 256;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder() ;
class SocketClient
private const int port = 11000;
private bool timeout = true;
private ManualResetEven t connectDone = new ManualResetEven t(false);
private ManualResetEven t sendDone = new ManualResetEven t(false);
private ManualResetEven t receiveDone = new ManualResetEven t(false);
[STAThread]
static void Main(string[] args)
SocketClient socketClient = new SocketClient();
socketClient.St artClient();
Console.ReadLin e();
private void StartClient()
IPHostEntry ipHostInfo = Dns.Resolve("lo calhost");
IPAddress ipAddress = ipHostInfo.Addr essList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAd dress, port);
Socket client = new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p);
client.BeginCon nect( remoteEP, new AsyncCallback(C onnectCallback) ,
client);
connectDone.Wai tOne();
for(int i=0; i<3; i++)
Send(client,"Th is is a test<EOF>" + i);
sendDone.WaitOn e();
Receive(client) ;
receiveDone.Wai tOne(3000, true);
if(timeout == true)
Console.WriteLi ne("Timed out...");
Console.WriteLi ne("Response received");
client.Shutdown (SocketShutdown .Both);
client.Close();
catch (Exception e)
Console.WriteLi ne(e.ToString() );
private void ConnectCallback (IAsyncResult ar)
Socket client = (Socket) ar.AsyncState;
client.EndConne ct(ar);
connectDone.Set ();
catch (Exception e)
Console.WriteLi ne(e.ToString() );
private void Receive(Socket client)
StateObject state = new StateObject();
state.workSocke t = client;
client.BeginRec eive( state.buffer, 0, StateObject.Buf ferSize, 0,
new AsyncCallback(R eceiveCallback) , state);
timeout = true;
catch (Exception e)
Console.WriteLi ne(e.ToString() );
private void ReceiveCallback ( IAsyncResult ar )
timeout = false;
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocke t;
int bytesRead = 0;
bytesRead = client.EndRecei ve(ar);
catch(ObjectDis posedException)
//the socket has been closed
if (bytesRead > 0)
state.sb.Append (Encoding.ASCII .GetString(stat e.buffer,0,byte sRead));
receiveDone.Set ();
//disconnected
receiveDone.Set ();
catch (Exception e)
Console.WriteLi ne(e.ToString() );
private void Send(Socket client, String data)
byte[] byteData = Encoding.ASCII. GetBytes(data);
client.BeginSen d(byteData, 0, byteData.Length , 0, new
AsyncCallback(S endCallback), client);
private void SendCallback(IA syncResult ar)
Socket client = (Socket) ar.AsyncState;
int bytesSent = client.EndSend( ar);
sendDone.Set();
catch (Exception e)
Console.WriteLi ne(e.ToString() );
The code above works fine and the server only sends data back to the
client when "This is a test<EOF>2" is received otherwise I have a
timeout. The output of this is:
Timed out...
Timed out...
Response received
However the beginReceive function is called twice without the
ReceiveCallback function being called. The ReceiveCallback function
is only called the third time the server sends the data back to the
client. When the client.Close() function is called the
ReceiveCallback function is called twice, since there were 2 receive
functions pending. The ReceiveCallback function calls EndReceive
which in turn throws an ObjectDisposedE xception which I catch and
ignore.
Here is my question, is this the proper way to implement a timeout
with an asynchronous socket or is it a bad idea to call beginReceive
with a pending receive ?
Ólafur Helgi.