// This method closes the read socket and gets rid of our user token associated with it private void CloseReadSocket(OSUserToken token, SocketAsyncEventArgs readSocket) { token.Dispose(); // Decrement the counter keeping track of the total number of clients connected to the server. Interlocked.Decrement(ref numconnections); // Put the read socket back in the stack to be used again socketpool.Push(readSocket); }
// This method processes the read socket once it has a transaction private void ProcessReceive(SocketAsyncEventArgs readSocket) { // if BytesTransferred is 0, then the remote end closed the connection if (readSocket.BytesTransferred > 0) { //SocketError.Success indicates that the last operation on the underlying socket succeeded if (readSocket.SocketError == SocketError.Success) { OSUserToken token = readSocket.UserToken as OSUserToken; if (token.ReadSocketData(readSocket)) { Socket readsocket = token.OwnerSocket; // If the read socket is empty, we can do something with the data that we accumulated // from all of the previous read requests on this socket if (readsocket.Available == 0) { token.ProcessData(readSocket); } // Start another receive request and immediately check to see if the receive is already complete // Otherwise OnIOCompleted will get called when the receive is complete // We are basically calling this same method recursively until there is no more data // on the read socket bool IOPending = readsocket.ReceiveAsync(readSocket); if (!IOPending) { ProcessReceive(readSocket); } } else { Console.WriteLine(token.LastError); CloseReadSocket(readSocket); } } else { ProcessError(readSocket); } } else { CloseReadSocket(readSocket); } }
// This overload of the close method doesn't require a token private void CloseReadSocket(SocketAsyncEventArgs readSocket) { OSUserToken token = readSocket.UserToken as OSUserToken; CloseReadSocket(token, readSocket); }