Language: EN

comunicacion-tcp-con-c

TCP Communication with C#

In this post we are going to establish a connection between devices using TCP with C#, taking advantage of the power and versatility provided by the .NET framework. TCP communication is one of the simplest and most convenient ways to transmit information in networked systems.

The applications of this type of communication are endless. We can send alerts for events, record remotely captured data, monitor systems, or control a system remotely, or even communicate between multiple virtualized machines. All of these are examples of countless applications in both automation and computer science.

To establish our TCP connection we will need two different programs:

  • A TCP Server, which is the program that listens and collects communications.
  • One or more TCP Clients, which are the programs that initiate communications with a TCP Server, which must be previously listening.

One of the first tasks in our design will be to determine which subsystem will assume each function. It will be to determine which of your subsystems assumes the function of Server and which of Client.

Finally, certain basic aspects of telecommunications are assumed, such as the need to have visibility between devices, know their IPs (at least the TCP Server’s), have the ports open, and, if necessary, correctly routed. For testing, we can use a single computer using the localhost address, 127.0.0.1).

TCP Server

The TCP Server is started first, listening on a range of IPs and on a specific port. In our case, we configure the TCP Server to accept connections from any IP, and on port 8010.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace TCPExample
{
    class TCPServer
    {
        public TCPServer()
        {
            try
            {
                TcpListener myList = new TcpListener(IPAddress.Any, 8010);
                myList.Start();

                Console.WriteLine("Server running at port 8001...");
                Console.WriteLine("Waiting for a connection...");

                Socket s = myList.AcceptSocket();
                Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

                byte[] b = new byte[100];
                int k = s.Receive(b);
                Console.WriteLine("Recieved...");
                for (int i = 0; i < k; i++)
                    Console.Write(Convert.ToChar(b[i]));

                ASCIIEncoding asen = new ASCIIEncoding();
                s.Send(asen.GetBytes("The string was recieved by the server."));
                Console.WriteLine("\nSent Acknowledgement");
                /* clean up */
                s.Close();
                Console.Read();
                myList.Stop();

            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.StackTrace);
                Console.Read();
            }
        }

    }
}

TCP Client

The TCP Client initiates communication by establishing a connection with the TCP Server. To do this, we have to indicate the IP and port on which the TCP Client is running. In this case, we save the IP address of the TCP Server in a configuration file called “conf.ini” that we will place in the same folder as the TCP Client.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace TCPExample
{
    class TCPClient
    {
        public TCPClient()
        {
            try
            {
                string ip;
                using (System.IO.StreamReader file = new System.IO.StreamReader("conf.ini"))
                {
                    ip = file.ReadLine();
                }

                IPAddress ipAd = IPAddress.Parse(ip);       

                TcpClient tcpclnt = new TcpClient();
                Console.WriteLine("Connecting...");

                tcpclnt.Connect(ip, 8010);

                Console.WriteLine("Connected");
                Console.Write("Enter the string to be transmitted : ");

                String str = Console.ReadLine();
                Stream stm = tcpclnt.GetStream();

                ASCIIEncoding asen = new ASCIIEncoding();
                byte[] ba = asen.GetBytes(str);
                Console.WriteLine("Transmitting...");

                stm.Write(ba, 0, ba.Length);

                byte[] bb = new byte[100];
                int k = stm.Read(bb, 0, 100);

                for (int i = 0; i < k; i++)
                    Console.Write(Convert.ToChar(bb[i]));

                Console.Read();
                tcpclnt.Close();
            }

            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.StackTrace);
                Console.Read();
            }
        }
    }
}