TCP level communication with C# .NET: the client

In this post we saw how to set up a very simplistic TCP listener that a TCP client can connect to. We built a short demo code that can be called in a console application.

The client code is even simpler:

static void Main(string[] args)
	TcpClient tcpClient = new TcpClient("localHost", 42000);
	using (NetworkStream ns = tcpClient.GetStream())
		using (BufferedStream bs = new BufferedStream(ns))
			byte[] messageBytesToSend = Encoding.UTF8.GetBytes("This is a very serious message from the client over TCP.");
			bs.Write(messageBytesToSend, 0, messageBytesToSend.Length);

	Console.WriteLine("Main done...");

We connect to localhost port number 42000, i.e. the address we set up in the post on the server side of the communication. We then use a NetworkStream object wrapped within a buffered stream to send a message to the TCP listener. We convert the string into a byte array and send it over the network.

Put the above code into another C# console application. Start the TCP listener console app first and then run the client. The listener should be able to read the message from the client:

TCP communication basics

View the list of posts on Messaging here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: