Learn C# Socket Programming

Making a Connection and Sending Data

With this info lets now try to check the code behind this:

Socket programming in .NET is made possible by the Socket class present inside the System.Net.Sockets namespace. This 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.Tcp);

The first parameter is the address family which we will use, in this case, interNetwork (which is IP version 4) - other options include Banyan NetBios, AppleTalk 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 this 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. This means the call will block (wait) 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.

You might also like...



Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“C++ : Where friends have access to your private members.” - Gavin Russell Baker