public static void ConnectedToServer(IAsyncResult state_in_an_ar_object) { SocketState ss = (SocketState)state_in_an_ar_object.AsyncState; try { // Complete the connection. ss.theSocket.EndConnect(state_in_an_ar_object); ss.callbackFunction(theServer); ss.theSocket.BeginReceive(ss.messageBuffer, 0, ss.messageBuffer.Length, SocketFlags.None, ReceiveCallback, ss); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Unable to connect to server. Error occured: " + e); return; } }
private static void ReceiveCallback(IAsyncResult ar) { SocketState ss = (SocketState)ar.AsyncState; int bytesRead = ss.theSocket.EndReceive(ar); // If the socket is still open if (bytesRead > 0) { string theMessage = Encoding.UTF8.GetString(ss.messageBuffer, 0, bytesRead); // Append the received data to the growable buffer. // It may be an incomplete message, so we need to start building it up piece by piece ss.sb.Append(theMessage); ss.callbackFunction(ss); } // Continue the "event loop" that was started on line 154. // Start listening for more parts of a message, or more new messages // ss.theSocket.BeginReceive(ss.messageBuffer, 0, ss.messageBuffer.Length, SocketFlags.None, ReceiveCallback, ss); }