Socket Programming in C# - Part I

Started by sams.raghu, Apr 08, 2008, 09:39 PM

previous topic - next topic
Go Down


Socket Programming in C#

Network programming in windows is possible with sockets. A socket is like a handle to a file. Socket programming resembles the file IO as does the Serial Communication. You can use sockets programming to have two applications communicate with each other. The application are typically on the different computers but they can be on same computer. For the two applications to talk to each either on the same or different computers using sockets one application is generally a server that keeps listening to the incoming requests and the other application acts as a client and makes the connection to the server application.

The server application can either accept or reject the connection. If the  server accepts the connection, a dialog can begin with between the client and the server.  Once the client is done with whatever it needs to do it can close the connection with the server. Connections are expensive in the sense that servers allow finite connections to occur.  During the time client has an active connection it can send the data to the server and/or receive the data.

The complexity begins here. When either side (client or server) sends data the other side is supposed to read the data. But how will the other side know when data has arrived. There are two options - either the application needs to poll for the data at regular intervals or there needs to be some sort of mechanism that would enable application to get notifications and application can read the data at that time. Well , after all Windows is an event driven system and the notification system seems an obvious and best choice and it in fact is.

As I said the two applications that need to communicate with each other    need to make a connection first. In order for the two application to make connections the two applications need to identify each other ( or each other's computer ). Computers on network have a unique identifier called  I.P. address which is represented in dot-notation like etc. Lets see how all this works in .NET.

System.Net.Sockets Namespace

Before we go any further, download the source code attached with this article. Extract the zip file to a folder say c:\Temp you will see following two folders :

* Server
* Client

In the Server folder there will be one EXE . And in the client there will be the source code in C# that is our client. There will be one file called SocketClient.sln  which the solution file . If you double click that your VS.NET will be launched and you will see the  project SocketClientProj in the solution. Under this project you will have SocketClientForm.cs file.  Now build the code ( by pressing Ctrl-Shift-B) and run the code you will see the following dialog box:

As you can see the dialog box has a field for Host IP address ( which is the IP address of the machine on which you will run the Server Application ( located under Server folder) ). Also there is a field where you can specify port number at which the Server is listening. The server app I have provided here listens at port 8221. So I have specified port to be 8221.

After specifying these parameters we need to connect to the server. So pressing Connect will connect to the server and to close the connection press Close. To send some data to the server type some data in the field near the button name Tx and if you press Rx the application will block unless there is some data to read.
With this info lets now try to check the code behind this:

Socket programming in .NET is made possible by Socket class present inside the System.Net.Sockets namespace.
Socket class  has several method and properties and a constructor.
The first step is to create an object of this class.
Since there is only one constructor we have no choice but to use it.

Here is how to create the socket:

m_socListener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.IP);

The first parameter is the address family which we will use interNetwork - other options include Banyan NetBios etc.
AddressFamily is an enum defined in Sockets namespace.
Next we need to specify socket type: and we would use reliable two way connection-based sockets (stream) instead of un-reliable Connectionless sockets ( datagrams) . So we obviously specify stream as the socket type and finally we are using TCP/IP so we would specify protocol type as Tcp.

Once we have created a Socket we need to make a connection to the server since we are using connection-based communication.
To connect to the remote computer  we need to know the IP Address and port at which to connect.
In .NET there is a class under System.Net namespace called IPEndPoint which represents a network computer  as an IP address and a port number.

The IPEndPoint has two  constructors - one that takes a IP Address and Port number  and one that takes long and port number. Since we have computer IP address we would use the former

public IPEndPoint(System.Net.IPAddress address, int port);

As you can see the first parameter takes a IPAddress object. If you examine the IPAddress class you will see that it has a static method called Parse that returns IPAddress given a string ( of dot notation ) and second parameter will be the port number. Once we have endpoint ready we can use Connect method of Socket class to connect to the end point  ( remote server computer ).
Here is the code:

System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("");
System.Net.IPEndPoint remoteEP = new IPEndPoint (iAdd,8221);
m_socClient.Connect (remoteEP);

These three lines of code will make a connection to the remote host running on computer with IP and listening at port 8221. If the Server is running and started ( listening ), the connection will succeed. If however the server is not running an exception called SocketException will be thrown. If you catch the   exception and check the Message property of the exception in this case you see following text:

"No connection could be made because the target machine actively refused it."

Similarly if you already have made a connection and the server somehow dies , you will get following exception if you try to send data.

"An existing connection was forcibly closed by the remote host"

Assuming that the connection is made, you can send data to other side using the Send method of the Socket class.
Send method has several overloads. All of them take a byte array . For example if you want to send "Hello There" to host you can use following call:

String szData = "Hello There";
byte[] byData = System.Text.Encoding.ASCII.GetBytes(szData);
catch (SocketException se)
MessageBox.Show ( se.Message );

Note that the Send method is blocking. What it means the call will block till the data has been sent or an exception has been thrown. There is an non-blocking version of the send which we will discuss in the next part of this article.
Similar to Send there is a Receive method on the Socket class. You can receive data using following call:

byte [] buffer = new byte[1024];
int iRx = m_socClient.Receive (buffer);

The Receive method again is blocking. It means that if there is no data available the call will block until some data arrives or an  exception   is thrown.

Non-blocking version of Receive method is more useful than the non-blocking version of Send because if we opt for block Receive , we are effectively doing polling. There is no events about data arrival. This model does not work well for serious applications. But all that is the subject of our next part of this article. For now we will settle with the blocking version.
In order to use the source code and application here you would need to run the Server first:

Here is the way Server looks like:

When you launch the Server, click Start to start listening. The Server listens at port 8221. So make sure you specify the port number 8221 in the port field of our client application. And in the IPAddress field of Client App enter the IP Address of the machine on which the Server is running. If you send some data to server from the client by pressing Tx button, you will see that data in the grayed out edit box.

Go Up

Quick Reply

With Quick-Reply you can write a post when viewing a topic without loading a new page. You can still use bulletin board code and smileys as you would in a normal post.

Warning: this topic has not been posted in for at least 120 days.
Unless you're sure you want to reply, please consider starting a new topic.

Note: this post will not display until it's been approved by a moderator.
Please leave this box empty:

Type the letters shown in the picture
Listen to the letters / Request another image

Type the letters shown in the picture:

shortcuts: alt+s submit/post or alt+p preview
IT Acumens Web Design Chennai | GinGly :: Mobile SMS Backup | CineBuzz :: Latest Cinema News | My Kids Diary :: Kids magical moment :: Book domain name @ 99 Rs monthly
Copyright 2005 - 2019 :: IT Acumens :: All Rights Reserved.
ITAcumens Forum with 2 lakhs post running for 14 years - Powered by IT Acumens Dedicated Server