// This method is called by I/O Completed() when an asynchronous send completes. // If all of the data has been sent, then this method calls StartReceive //to start another receive op on the socket to read any additional // data sent from the client. If all of the data has NOT been sent, then it //calls StartSend to send more data. private void ProcessSend(SocketAsyncEventArgs receiveSendEventArgs) { DataHolderToken token = (DataHolderToken)receiveSendEventArgs.UserToken; if (receiveSendEventArgs.SocketError == SocketError.Success) { token.sendBytesRemainingCount = token.sendBytesRemainingCount - receiveSendEventArgs.BytesTransferred; if (token.sendBytesRemainingCount == 0) { // If we are within this if-statement, then all the bytes in // the message have been sent. token.Reset(); CloseClientSocket(receiveSendEventArgs); } else { // If some of the bytes in the message have NOT been sent, // then we will need to post another send operation, after we store // a count of how many bytes that we sent in this send op. token.bytesSentAlreadyCount += receiveSendEventArgs.BytesTransferred; // So let's loop back to StartSend(). StartSend(receiveSendEventArgs); } } else { // We'll just close the socket if there was a // socket error when receiving data from the client. token.Reset(); CloseClientSocket(receiveSendEventArgs); } }
/// <summary> /// This method is invoked when an asynchronous receive operation completes. If the /// remote host closed the connection, then the socket is closed. If data was received then /// the data is echoed back to the client. /// </summary> private void ProcessReceive(SocketAsyncEventArgs receiveSendEventArgs) { DataHolderToken token = (DataHolderToken)receiveSendEventArgs.UserToken; //If there was a socket error, close the connection if (receiveSendEventArgs.SocketError != SocketError.Success) { token.Reset(); CloseClientSocket(receiveSendEventArgs); //Jump out of the ProcessReceive method. return; } // If no data was received, close the connection. This is a NORMAL // situation that shows when the client has finished sending data. if (receiveSendEventArgs.BytesTransferred == 0) { token.Reset(); CloseClientSocket(receiveSendEventArgs); return; } //Assume that all of the bytes transfered is the received message token.dataMessageReceived = new Byte[receiveSendEventArgs.BytesTransferred]; Buffer.BlockCopy(receiveSendEventArgs.Buffer, token.receiveBufferOffset, token.dataMessageReceived, 0, receiveSendEventArgs.BytesTransferred); // Decode the byte array received in the token //string sBuffer = Encoding.ASCII.GetString(bReceive); string sBuffer = Encoding.UTF8.GetString(token.dataMessageReceived); //At present we will only deal with GET type if (sBuffer.Substring(0, 3) != "GET") { token.Reset(); CloseClientSocket(receiveSendEventArgs); } else { // Look for HTTP request int iStartPos = sBuffer.IndexOf("HTTP", 1); // Get the HTTP text and version e.g. it will return "HTTP/1.1" sHttpVersion = sBuffer.Substring(iStartPos, 8); // Extract the Requested Type and Requested file/directory String sRequest = sBuffer.Substring(5, iStartPos - 1 - 5); sRequest = HttpUtility.UrlDecode(sRequest); token.httpRequest = sRequest.TrimEnd(); StartSendRequest(receiveSendEventArgs); } }
//Post a send. private void StartSend(SocketAsyncEventArgs receiveSendEventArgs) { DataHolderToken token = (DataHolderToken)receiveSendEventArgs.UserToken; int count = 0; try { //The number of bytes to send depends on whether the message is larger than //the buffer or not. If it is larger than the buffer, then we will have //to post more than one send operation. If it is less than or equal to the //size of the send buffer, then we can accomplish it in one send op. if (token.sendBytesRemainingCount <= (receiveBufferSize + settings.send_buffer_size)) { count = token.sendBytesRemainingCount; receiveSendEventArgs.SetBuffer(token.sendBufferOffset, count); //Copy the bytes to the buffer associated with this SAEA object. Buffer.BlockCopy(token.dataToSend, token.bytesSentAlreadyCount, receiveSendEventArgs.Buffer, token.sendBufferOffset, token.sendBytesRemainingCount); } else { logger.Write("Exceeded buffer size in StartSend method, total size = " + token.sendBytesRemainingCount); //We cannot try to set the buffer any larger than its size. //So since receiveSendToken.sendBytesRemainingCount > BufferSize, we just //set it to the maximum size, to send the most data possible. count = receiveBufferSize + settings.send_buffer_size; receiveSendEventArgs.SetBuffer(token.sendBufferOffset, count); //Copy the bytes to the buffer associated with this SAEA object. Buffer.BlockCopy(token.dataToSend, token.bytesSentAlreadyCount, receiveSendEventArgs.Buffer, token.sendBufferOffset, receiveBufferSize); } //post asynchronous send operation bool willRaiseEvent = receiveSendEventArgs.AcceptSocket.SendAsync(receiveSendEventArgs); if (!willRaiseEvent) { ProcessSend(receiveSendEventArgs); } } catch (Exception e) { logger.Write("Exception in SetBuffer in StartSend method of HttpServer.cs, offset=" + token.sendBufferOffset + ", count=" + count + ", Buffer=" + receiveSendEventArgs.Buffer + ": " + e.Message); token.Reset(); CloseClientSocket(receiveSendEventArgs); } }
// Does the normal destroying of sockets after // we finish receiving and sending on a connection. private void CloseClientSocket(SocketAsyncEventArgs e) { DataHolderToken token = (DataHolderToken)e.UserToken; // do a shutdown before you close the socket try { e.AcceptSocket.Shutdown(SocketShutdown.Both); } // throws if socket was already closed catch (Exception) { } //This method closes the socket and releases all resources, both //managed and unmanaged. It internally calls Dispose. e.AcceptSocket.Close(); //Make sure the new DataHolder has been created for the next connection. //If it has, then dataMessageReceived should be null. if (token.dataMessageReceived != null) { token.Reset(); } // Put the SocketAsyncEventArg back into the pool, // to be used by another client. This poolOfRecSendEventArgs.Push(e); // decrement the counter keeping track of the total number of clients //connected to the server, for testing Interlocked.Decrement(ref numConnectedSockets); if (numConnectedSockets + 1 == maxConnections) { logger.Write("Number of connected sockets: " + numConnectedSockets + " / " + maxConnections); } //Release Semaphore so that its connection counter will be decremented. //This must be done AFTER putting the SocketAsyncEventArg back into the pool, //or you can run into problems. maxNumberAcceptedClients.Release(); }
private void StartReceive(SocketAsyncEventArgs receiveSendEventArgs) { DataHolderToken token = (DataHolderToken)receiveSendEventArgs.UserToken; try { //Set the buffer for the receive operation. receiveSendEventArgs.SetBuffer(token.receiveBufferOffset, receiveBufferSize); // Post async receive operation on the socket. bool willRaiseEvent = receiveSendEventArgs.AcceptSocket.ReceiveAsync(receiveSendEventArgs); if (!willRaiseEvent) { ProcessReceive(receiveSendEventArgs); } } catch (Exception e) { logger.Write("Exception in SetBuffer in StartReceive method of HttpServer.cs, offset=" + token.receiveBufferOffset + ", count=" + receiveBufferSize + ", Buffer=" + receiveSendEventArgs.Buffer + ": " + e.Message); token.Reset(); CloseClientSocket(receiveSendEventArgs); } }