/// <summary> /// Accept the new client then invoke the call back /// </summary> /// <param name="ar"></param> private static void AcceptNewClient(IAsyncResult ar) { ConnectionState cs = (ConnectionState)ar.AsyncState; Socket socket = cs.listener.EndAcceptSocket(ar); SocketState ss = new SocketState(socket, clientID++); ss.theSocket = socket; ss.CallMe = cs.CallMe; ss.CallMe(ss); cs.listener.BeginAcceptSocket(AcceptNewClient, cs); }
// Ends the attempt to connect to server and fires the callback then begins to receive message private static void ConnectedToServer(IAsyncResult ar) { SocketState state = (SocketState)ar.AsyncState; try { state.theSocket.EndConnect(ar); state.CallMe(state); state.theSocket.BeginReceive(state.messageBuffer, 0, state.messageBuffer.Length, SocketFlags.None, RecieveCallback, state); } catch { System.Windows.Forms.MessageBox.Show("Unable to connect to Server"); } }
// receives a message so end receive, add to stringbuilder then fire the callback private static void RecieveCallback(IAsyncResult ar) { SocketState state = (SocketState)ar.AsyncState; try { int bytesRead = state.theSocket.EndReceive(ar); if (bytesRead == 0) { state.sb.Clear(); } else { state.sb.Append(Encoding.UTF8.GetString(state.messageBuffer, 0, bytesRead)); } state.CallMe(state); } catch { } }