/// <summary> /// The ReceiveCallback method is called by the OS when new data arrives. /// This method checks to see how much data has arrived. If 0, the connection has been closed /// (presumably by the server). On greater than zero data, this method calls the callback function /// provided above. /// </summary> /// <param name="state_in_an_ar_object"></param> public static void ReceiveCallback(IAsyncResult state_in_an_ar_object) { try { // Assign state object stored in the argument to new state object instance. SocketState state = (SocketState)state_in_an_ar_object.AsyncState; // Read the number of bytes received from the remote device. int bytes = state.Socket.EndReceive(state_in_an_ar_object); // If data has been received, get the data. if (bytes > 0) { // Read data from the remote device and store data received so far. string incomingData = Encoding.UTF8.GetString(state.Buffer, 0, bytes); state.Data.Append(incomingData); // Process the data received so far. ProcessData(state); // Call the function stored in the state object. state.Callback(state); } } catch (Exception e) { Debug.WriteLine("Unable to connect to remote host. Error occured: " + e); } }
/// <summary> /// This function is referenced by the BeginConnect method above and is "called" by the OS when the socket /// connects to the server. The "state_in_an_ar_object" object contains a field "AsyncState" which contains the /// "state" object saved away in the above function. /// /// Once a connection is established the "saved away" callbackFunction needs to called. This function is /// saved in the socket state, and was originally passed in to ConnectToServer. /// </summary> /// <param name="state_in_an_ar_object"></param> public static void ConnectedToServer(IAsyncResult state_in_an_ar_object) {// // Assign state object stored in the argument to new state object instance. SocketState state = (SocketState)state_in_an_ar_object.AsyncState; // Terminate the stored socket's request to connect to remote host. state.Socket.EndConnect(state_in_an_ar_object); // Call the callback function saved in the socket state. state.Callback(state); // Begin receiving data from the remote host. GetData(state); }
public static void ReceiveCallback(IAsyncResult ar) { // Get the socket state out of the AsyncState // This is the object that we passed to BeginReceive that represents the socket SocketState sender = (SocketState)ar.AsyncState; int bytesRead = sender.Socket.EndReceive(ar); // If the socket is still open if (bytesRead > 0) { string theMessage = Encoding.UTF8.GetString(sender.Buffer, 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 sender.Data.Append(theMessage); if (theMessage == "disconnect") { sender.Socket.Disconnect(false); } } sender.Callback(sender); }