Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata