Async Server Code Example

The following example demonstrates an Echo Server in a Windows Forms environment. The server uses on-demand IO completion threads to handle clients.

 

private void buttonStart_Click(object sender, EventArgs e)
{
    //Start the echo server on port 7.
    server1.Start(new ConnectThreadStart(acceptConnection), 7, null);
}

private void acceptConnection(TcpBase connection, object state)
{
    //This function executes on a worker thread.
    //An async Read is posted. The readAsyncCompleted callback will
    //execute when data is available.
    byte[] buffer = new byte[1024];
    connection.ReadAsync(buffer, 0, buffer.Length,
        new ReadAsyncCompleted(readAsyncCompleted), null);
}

private void readAsyncCompleted(TcpBase connection, Data data, object state)
{
    //This function executes when data has been read.
    //Echo data received back to the client and post an async Read.
    if (data != null)
    {
        connection.Write(data.Buffer, data.Offset, data.Count);
        connection.ReadAsync(data.Buffer, 0, data.Buffer.Length,
        new ReadAsyncCompleted(readAsyncCompleted), null);
    }
}

private void buttonStop_Click(object sender, EventArgs e)
{
    //Gracefully stop the echo server.
    server1.Close();
}