private void AcceptConnection(IAsyncResult ar) { allDone.Set(); try { Socket server = (Socket)ar.AsyncState; Socket client = server.EndAccept(ar); mClient = client; AcceptComplete(client); SocketData state = new SocketData(); state.Socket = client; client.BeginReceive(state.Buffer, 0, SocketData.BufferSize, 0, new AsyncCallback(ReadCallBack), state); } catch (ObjectDisposedException) { //this is the state we get to when the socket is closed } }
private void ReadCallBack(IAsyncResult ar) { String content = String.Empty; SocketData clientSocketData = (SocketData)ar.AsyncState; Socket client = clientSocketData.Socket; int bytesRead = client.EndReceive(ar); System.Console.WriteLine("Received {0} bytes of data", bytesRead); if (bytesRead > 0) { //store clientSocketData.StringBuild.Append(Encoding.ASCII.GetString(clientSocketData.Buffer, 0, bytesRead)); content = clientSocketData.StringBuild.ToString(); if (bytesRead < SocketData.BufferSize) { //all data is in content = content.TrimEnd(); Console.WriteLine("Read {0} bytes: \n Data: {1}", content.Length, content); DataReceived(content); clientSocketData.StringBuild.Clear(); if (content.IndexOf("BYE") > -1) { return; } } Console.WriteLine("Looking for more data"); //keep reading client.BeginReceive(clientSocketData.Buffer, 0, SocketData.BufferSize, 0, new AsyncCallback(ReadCallBack), clientSocketData); } }