TCP level communication with C# .NET: the client
March 10, 2016 Leave a comment
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:
View the list of posts on Messaging here.