/// <summary> /// Checks to see how much data has arrived. If there is no data, the connection is closed. /// If greater than zero, this method gets the SocketState object out of the IAsyncResult and the /// callMe function. /// </summary> /// <param name="stateAsArObject"></param> private static void ReceiveCallback(IAsyncResult stateAsArObject) { SocketState ss = (SocketState)stateAsArObject.AsyncState; try { int bytesRead = ss.theSocket.EndReceive(stateAsArObject); // 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.callMe(ss); } } catch (SocketException e) { Console.WriteLine("Client disconnected."); } }
/// <summary> /// Calls the callMe function once a connection with the server is established /// </summary> /// <param name="stateAsArObject"></param> private static void ConnectedCallback(IAsyncResult stateAsArObject) { SocketState ss = (SocketState)stateAsArObject.AsyncState; try { // Complete the connection. ss.theSocket.EndConnect(stateAsArObject); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Unable to connect to server. Error occured: " + e); return; } // Start an event loop to receive data from the server. ss.callMe(ss); }