TCP level communication with C# .NET with a server and a client

.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("127.0.0.1");
	TcpListener tcpListener = new TcpListener(localhost, 42000);
	tcpListener.Start();

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

	Console.WriteLine(messageBuilder.ToString());

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

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.

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...");
	Console.ReadKey();
}

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.

Advertisements

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:

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: