13.9. Writing a TCP Server

Problem

You need to create a server that listens on a port for incoming requests from a TCP client. These client requests can then be processed at the server, and any responses can be sent back to the client. Recipe 13.10 shows how to write a TCP client to interact with this server.

Solution

Use the TcpListener class to create a TCP-based endpoint to listen for requests from TCP based clients. RunServer initiates a one-request TCP-based server running on a given IP address and port:

public static void RunServer(string address,int port)
{
    // set up address
    IPAddress addr = IPAddress.Parse(address);
    // set up listener on that address/port
    TcpListener tcpListener = new TcpListener(addr,port);
    if(tcpListener != null)
    {
        // start it up
        tcpListener.Start( );
        // wait for a tcp client to connect
        TcpClient tcpClient = tcpListener.AcceptTcpClient( );
        
        byte [] bytes = new byte[1024];
        // get the client stream
        NetworkStream clientStream = tcpClient.GetStream( );
        StreamReader reader = new StreamReader(clientStream,Encoding.UTF8);
        try
        {
            string request = reader.ReadToEnd( );

            // just send an acknowledgement
            bytes = Encoding.UTF8.GetBytes("Thanks for the message!");
            clientStream.Write(bytes,0,bytes.Length);
        }
        finally
        {
            // close the reader
            reader.Close( );
        }
     
        // stop listening
        tcpListener.Stop( );

    }
}

Discussion

RunServer takes the IP address and port passed in, creates an IPAddress from the string address, and creates a TcpListener on that IPAddress and port. Once created, ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.