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 for this type of communication are endless. We can send alerts for events, remotely register captured data, monitor systems, control a system from a distance, or even communicate several virtualized machines. All of these are examples among a myriad of applications in both automation and computing.
To establish our TCP connection we will need two different programs:
- A TCP Server, which is the program that listens for and receives communications.
- One or several TCP Clients, which are the programs that initiate communication with a TCP Server, which must be listening beforehand.
One of the first tasks in our design will be to determine which subsystem will assume each function. We need to decide which of your subsystems takes on the Server role and which the Client role.
Finally, certain basic aspects of telecommunications are assumed, such as the need for visibility between devices, knowing their IPs (at least the TCP Server’s), having the ports open and, if necessary, correctly routed. For testing, we can use a single machine 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, 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 need to specify the IP and port where the TCP Server is running. In this case, we save the TCP Server’s IP address in a configuration file called “conf.ini” which 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();
}
}
}
}

