// Called when BeginReceive completes private static void ReceiveCallback(IAsyncResult ar) { TCPLineClient client = (TCPLineClient)ar.AsyncState; try { // Retrieve the state object and the client socket // from the asynchronous state object. Socket socket = client.socket; // Read data from the remote device. int bytesRead = socket.EndReceive(ar); if (bytesRead > 0) { // There might be more data, so store the data received so far. client.inData.Append(Encoding.ASCII.GetString(client.recvBuffer, 0, bytesRead)); // Signal that all bytes have been received. client.receiveInProgress = false; client.newData = true; } else { client.Close(); } } catch (Exception e) { client.Close(); } }
// Called when send completes private static void SendCallback(IAsyncResult ar) { TCPLineClient client = (TCPLineClient)ar.AsyncState; try { // Retrieve the socket from the state object. Socket socket = client.socket; // Complete sending the data to the remote device. int bytesSent = socket.EndSend(ar); } catch (Exception e) { client.Close(); } }
// Called when connect completes private static void ConnectCallback(IAsyncResult ar) { TCPLineClient client = (TCPLineClient)ar.AsyncState; try { // Retrieve the socket from the state object. Socket socket = client.socket; // Complete the connection. socket.EndConnect(ar); // Signal that the connection has been made. client.socketConnected = true; } catch (Exception e) { client.Close(); } }