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...");
	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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT BEST PRACTICES WITH MICROSOFT STACK & ANGULAR

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: