private void ProcessSend(SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { // done echoing data back to the client AsyncUserToken token = (AsyncUserToken)e.UserToken; // read the next block of data send from the client bool willRaiseEvent = token.Socket.ReceiveAsync(e); if (!willRaiseEvent) { ProcessReceive(e); } } else { CloseClientSocket(e); } }
public void SendMessage(SimpleSocketData data) { SocketAsyncEventArgs eventArgs = data.SimpleSocketEventArgs; string message = data.Message; if (null != message && message.Trim() != "") { // send the message byte[] buffer = Encoding.ASCII.GetBytes(message); eventArgs.SetBuffer(buffer, 0, message.Length); AsyncUserToken token = eventArgs.UserToken as AsyncUserToken; bool willRaiseEvent = token.Socket.SendAsync(eventArgs); if (!willRaiseEvent) { ProcessSend(eventArgs); } } }
private void ProcessReceive(SocketAsyncEventArgs e) { AsyncUserToken token = (AsyncUserToken)e.UserToken; // check if the remote host closed the connection if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success) { // Do data processing here string message = Encoding.ASCII.GetString(e.Buffer, e.Offset, e.BytesTransferred); OnReceive(e); // token.Socket.SendAsync(e); // start receiving again // token.Socket.ReceiveAsync(e); } else { // close client socket CloseClientSocket(e); } }
/// <summary> /// Close Socket connection with one of the connected Client socket /// </summary> /// <param name="e">SocketAsyncEvnetArgs object which have the socket of the client that /// we want to close connection</param> public void CloseClientSocket(SocketAsyncEventArgs e) { AsyncUserToken token = e.UserToken as AsyncUserToken; // close the socket associate with the client try { token.Socket.Shutdown(SocketShutdown.Send); } catch (Exception) { } // Decrease the number of connected socket client Interlocked.Decrement(ref numberOfConnectedSockets); maxNumberOfConnectedSocket.Release(); // Free the SocketAsyncEventArg so they can be reused by another client readWritePool.Push(e); OnClientDisconnected(); // Cant seem to find socket close so chekcing if shutdown close the socket connection or not // PrintIfSocketIsClosedOrNot(token.Socket); }