/// <summary> /// This function is called when new data arrives. /// </summary> /// <param name="ar"></param> private static void ReceiveCallback(IAsyncResult ar) { SocketState ss = (SocketState)ar.AsyncState; if (ss.TheSocket.Connected == false) { return; } try { int bytesRead = ss.TheSocket.EndReceive(ar); // If the socket is still open if (bytesRead > 0) { string theMessage = Encoding.UTF8.GetString(ss.MessageBuffer, 0, bytesRead); ss.SB.Append(theMessage); if (ss.CallBackFunction != null) { ss.CallBackFunction(ss); } } else { ss.ID = 0; } } catch (Exception e) { ss.TheSocket.Close(); return; } }
/// <summary> /// A callback invoked when a send operation completes, will invoke a callback function after send end. /// </summary> /// <param name="ar"></param> private static void SendCallbackWithFunc(IAsyncResult ar) { SocketState ss = (SocketState)ar.AsyncState; // Nothing much to do here, just conclude the send operation so the socket is happy. ss.TheSocket.EndSend(ar); ss.CallBackFunction(ss); }
/// <summary> /// This function is called when the remote site acknowledges connect request /// </summary> /// <param name="ar"></param> private static void ConnectToServer(IAsyncResult ar) { SocketState ss = (SocketState)ar.AsyncState; try { // Complete the connection. ss.TheSocket.EndConnect(ar); } catch (Exception e) { Debug.WriteLine("Unable to connect to server. Error occured: " + e); return; } if (ss.CallBackFunction != null) { ss.CallBackFunction(ss); } }