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.10. Writing a TCP Client

Problem

You want to interact with a TCP-based server.

Solution

Use the TcpClient class to connect to and converse with a TCP-based server by passing the address and port of the server to talk to. This example will talk to the server from Recipe 13.9:

public string RunClient(string address,int port)
{
    string response = "";
    // Set up a listener on that address/port
    TcpClient tcpClient = new TcpClient(address,port);
    if(tcpClient != null)
    {
        string message = "Hello there";
        // Translate the passed message into UTF8ASCII and store it as a Byte array.
        byte[] bytes = Encoding.ASCII.GetBytes(message);         

        NetworkStream stream = tcpClient.GetStream( );

        // Send the message to the connected TcpServer. 
        // The write flushes the stream automatically here
        stream.Write(bytes, 0, bytes.Length);

        // Get the response from the server

        StreamReader reader = new StreamReader(stream,Encoding.UTF8);
        try
        {
            response = reader.ReadToEnd( );
        }
        finally
        {
            // Close the reader
            reader.Close( );
        }

        // Close the client
        tcpClient.Close( );
    }
    // Return the response text
    return response;
}

Discussion

RunClient is designed to send one message containing “Hello World” to the server, get the response and return it as a string, then terminate. To accomplish this, it creates the TcpClient on the address and port passed in, and then it gets the bytes for the string using the Encoding.UTF8.GetBytes method. Once it has the bytes to send, it gets the NetworkStream from the TcpClient by calling the GetStream ...

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