In this article, learn C# socket programming. First, we will see how to create a C# socket and setup a listener server node that starts listening to any messages coming its way via the predefined IP and protocol. We will also see how to create a client application that will send messages to a listener server and read it using Sockets. The sample code is written in C# and .NET Core.
Sockets in computer networks are used to establish a connection between two or more computers and used to send data from one computer to another. Each computer in the network is called a node. Sockets use nodes’ IP addresses and a network protocol to create a secure channel of communication and use this channel to transfer data.
Socket client and server communication.
In socket communication, one node acts as a listener and other node acts as a client. The listener node opens itself upon a pre-established IP address and on a predefined protocol and starts listening. Clients who want to send messages to the server start broadcasting messages on the same IP address and same protocol. A typical socket connection uses the Transmission Control Protocol (TCP) to communicate.
In this article, we will see how to create a socket and setup a listener server node that starts listening to any messages coming to it via the predefined IP and protocol. We will also see how to create a client application that will send message to the listener server and read it. The sample code is written in C# and .NET Core.
Step 1 - Create a Listener
Create a .NET Core Console app and write the following code listed in Listing 1.
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
-
-
-
- public class SocketListener
- {
- public static int Main(String[] args)
- {
- StartServer();
- return 0;
- }
-
-
- public static void StartServer()
- {
-
-
-
- IPHostEntry host = Dns.GetHostEntry("localhost");
- IPAddress ipAddress = host.AddressList[0];
- IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
-
-
- try {
-
-
- Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
-
- listener.Bind(localEndPoint);
-
-
- listener.Listen(10);
-
- Console.WriteLine("Waiting for a connection...");
- Socket handler = listener.Accept();
-
-
- string data = null;
- byte[] bytes = null;
-
- while (true)
- {
- bytes = new byte[1024];
- int bytesRec = handler.Receive(bytes);
- data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
- if (data.IndexOf("<EOF>") > -1)
- {
- break;
- }
- }
-
- Console.WriteLine("Text received : {0}", data);
-
- byte[] msg = Encoding.ASCII.GetBytes(data);
- handler.Send(msg);
- handler.Shutdown(SocketShutdown.Both);
- handler.Close();
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
-
- Console.WriteLine("\n Press any key to continue...");
- Console.ReadKey();
- }
- }
Listing 1.
The code listed in Listing 1 creates a Socket listener on the local host using TCP protocol and any messages captured from the client, it displays it on the console. The listener can request 10 clients at a time and the 11th request will give a server busy message.
The output will look like Figure 1.
Figure 1.
Step 2 - Create a Client
A client application is the one that establishes a connection with a server/listener and send a message. Create another .NET Core console application and write the following code in Listing 2.
The sample code in Listing 2 creates a client application that creates a socket connection with the listener on the given IP and the port, and sends a message.
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
-
-
-
-
- public class SocketClient
- {
- public static int Main(String[] args)
- {
- StartClient();
- return 0;
- }
-
-
- public static void StartClient()
- {
- byte[] bytes = new byte[1024];
-
- try
- {
-
-
-
-
- IPHostEntry host = Dns.GetHostEntry("localhost");
- IPAddress ipAddress = host.AddressList[0];
- IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
-
-
- Socket sender = new Socket(ipAddress.AddressFamily,
- SocketType.Stream, ProtocolType.Tcp);
-
-
- try
- {
-
- sender.Connect(remoteEP);
-
- Console.WriteLine("Socket connected to {0}",
- sender.RemoteEndPoint.ToString());
-
-
- byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
-
-
- int bytesSent = sender.Send(msg);
-
-
- int bytesRec = sender.Receive(bytes);
- Console.WriteLine("Echoed test = {0}",
- Encoding.ASCII.GetString(bytes, 0, bytesRec));
-
-
- sender.Shutdown(SocketShutdown.Both);
- sender.Close();
-
- }
- catch (ArgumentNullException ane)
- {
- Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
- }
- catch (SocketException se)
- {
- Console.WriteLine("SocketException : {0}", se.ToString());
- }
- catch (Exception e)
- {
- Console.WriteLine("Unexpected exception : {0}", e.ToString());
- }
-
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
- }
- }
Listing 2.
Step 3 - Test and Run
Now build both projects and run both applications from the command line. You will see the message sent by the client is read and displayed by the listener.
Once client runs, you will see the message is sent to the server. See Figure 2
Figure 2.
Summary
In this article, you learned how to use Sockets in C# and .NET Core to create a client and a server to communicate via the TCP/IP protocol. This sample works on local machine but you can use the same code on a network. All you need to do is change the IP address of the host.