TCP level communication with C# .NET: the server

.NET has the necessary objects to enable TCP-level messaging in the System.Net.Sockets namespace. The key objects to build an extremely simple TCP server are TcpListener and Socket. The TCP client and server can communicate in a stream-like fashion over the network using the NetworkStream object.

Here’s an example of how a TCP server can ingest the message of a single client:

static void Main(string[] args)
	IPAddress localhost = IPAddress.Parse("");
	TcpListener tcpListener = new TcpListener(localhost, 42000);

	Socket tcpClient = tcpListener.AcceptSocket();
	int bytesRead = 0;
	StringBuilder messageBuilder = new StringBuilder();
	using (NetworkStream ns = new NetworkStream(tcpClient))
		int messageChunkSize = 10;				
			byte[] chunks = new byte[messageChunkSize];
			bytesRead = ns.Read(chunks, 0, chunks.Length);
		while (bytesRead != 0);


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

We declare a TCP listener on port 42000 on localhost. You might need to adjust the port number of it’s in use on your machine. We then start the listener and call the AcceptSocket method which will block code execution until a client joins. Then as soon as the client joins we read their message in chunks of 10 bytes and append each chunk to a string builder. We repeat this loop until the size of the received byte array is 0, i.e. there’s nothing else to read from the network stream.

You can put the above code in a C# console application. We’ll see in the post on the client side how a client can send a message to this listener.

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: