Socket Programming with C#

In this article, we will learn the basics of socket programming using C#. Secondly, we will create a small sample consisting of a server and a client which will communicate using TCP protocols.

You can download the solution package for this example at the bottom of the post.

About TCP/IP

There are two types of communication protocol uses for Socket Programming in C#, they are TCP/IP (Transmission Control Protocol/Internet protocol) Communication and UDP/IP (User Datagram Protocol/Internet protocol) Communication .

A Socket is an End-Point of To and From (Bidirectional) communication link between two programs (Server Program and Client Program ) running on the same network . We need two programs for communicating a socket application in C#. A Server Socket Program ( Server ) and a Client Socket Program ( Client ) .

Pre-requisites

Should have good knowledge of C#.

Basic knowledge of socket programming.

TCP C# Socket sample

Under TCP there is a clear distinction between the server process and the client process.

Server Socket

A Server Socket running on a computer has a socket that bound to a Port Number on the same computer and listening to the client’s incoming requests.

The basic steps to create a TCP/IP server are as follows:

  1. Create aNet.Sockets.TcpListener with a given local port and start it. Here we assign a Port No. 8888 for the Server Socket , it is an instance of the C# Class TcpListener , and call its start() method.
1
2
TcpListener serverSocket = new TcpListener(8888);
serverSocket.Start();
TcpListener serverSocket = new TcpListener(8888);
serverSocket.Start();
  1. Wait for the incoming connection request and accept a System.Net.Sockets.Socket object from the listener whenever the request appears:
1
2
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
  1. Create a System.Net.Sockets.NetworkStream from the above Socket:
1
NetworkStream networkStream = clientSocket.GetStream();
NetworkStream networkStream = clientSocket.GetStream();
  1. Communicate with the client using the predefined protocol (well established rules for data exchange):

You can create an infinite loop for monitoring the request from Client’s side. When the Server Socket accept a request from the Client side, it reads the data from NetworkStream and also it write the response to NetworkStream .

  1. Close theStream
  2. Close theSocket:
1
2
clientSocket.Close();
serverSocket.Stop();
clientSocket.Close();
serverSocket.Stop();

Client Socket

Next, we are going to create a client program.

The Client is a Windows based application. The Client is connected to the Port 8888 of the Server, and the IP Address (Computer Name) here we give as 127.0.0.1, because the Server and Client running on the same machine .

After creating a form like this:

tcp1

You can follow these basic steps for creating a TCP/IP client:

  1. Create a“System.Net.Sockets.TcpClient” using the server’s host name or your PC’s Ip and port then connect to server:
1
2
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
clientSocket.Connect("127.0.0.1", 8888);
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
clientSocket.Connect("127.0.0.1", 8888);
  1. Obtain the stream from the aboveTCPClient.
1
NetworkStream serverStream = clientSocket.GetStream();
NetworkStream serverStream = clientSocket.GetStream();
  1. Communicate with the server using the predefined protocol.

When the Client program starts, it will connect to the  Server Socket Program and start to reads data from NetworkStream, and also write to the NetworkStream .

How does it work?

First, you have to start Server. You will get a message “Server Started ” in your DOS screen, where the server program is running.

tcp2

Start Client in the same computer or other computers on the same network. When you start the client program, it will establish a connection to the Server and get a message in client screen “ Client Started “, at the same time you can see a message in the Server screen “ Accept connection from client “.

tcp3

Now your Server and Client is get connected and communicated. If you want to communicate the Server and Client again, click the button in the client program, then you can see new messages in the Server and Client programs displayed.

Notice

When run your program, you may get an error on the line:

1
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);

The error shows the following: “Specified argument was out of the range of valid values. Parameter name: size”

The reason is: ReceiveBufferSize might be bigger than your buffer. It’s an example of a buffer overflow.

You change your size of your buffer and enjoy yourself – Your first TCP program will be perfect!

  1. 6. In Summary
  • A Server services therequests from the client.
  • The client is usually the
  • A single server accommodates multiple clients.
  • The server is responsible for thedata processing/operations while the client handles the presentation.

Download the source code TCPSocket

About The Author

Hao Nguyen

Contributors

Plaintutorials.com contributors

Leave a Reply