Exemple #1
0
    // This handles a send event on a particular client socket that has
    // connected. We transmit back to them the data that we originally read, as
    // a sort of echo.
    private void SendCallback(IAsyncResult ar)
    {
        try
        {
            sendMutex.WaitOne();

            BuildClient client = (BuildClient)ar.AsyncState;
            Socket      socket = client.socket;

            // Complete the transmission of the data to the remote end and
            // indicate that we did so.
            int bytesSent = socket.EndSend(ar);
            // Console.WriteLine("Sent {0} bytes to client.", bytesSent);
            client.bytesSent += bytesSent;

            if (client.bytesSent == client.sendBuffer.Length)
            {
                // Console.WriteLine("Send: Complete");
                client.sendBuffer = null;
                client.bytesSent  = 0;

                if (client.closeAfterSending)
                {
                    Console.WriteLine("Closing connection");
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Disconnect(true);
                    return;
                }
            }

            // Trigger another send; if this send was complete, then this will
            // check and see if there's another message that we can send, but
            // if this send was not complete, then we'll try to finish the job.
            client.BeginSending();
        }

        catch (SocketException se)
        {
            Console.WriteLine("Socket Error: {0}", se.Message);
            Console.WriteLine("Closing connection");
        }

        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        finally
        {
            sendMutex.ReleaseMutex();
        }
    }