Click here to Skip to main content
13,250,453 members (50,549 online)
Click here to Skip to main content
Add your own
alternative version


194 bookmarked
Posted 23 Sep 2012

Working with Sockets in C#

, 31 May 2013
Rate this:
Please Sign up or sign in to vote.
This article shows how to use sockets to send messages


Sockets are getting more and more used nowadays. They provide a simple way to exchange data over the network. It's used, as an example, to exchange messages between users. You can go further more to transfer files and play "distributed" games and communicate multiple programs. Thanks to its powerful features, sockets are becoming a must to learn technology for developers.

As sockets are based on client/server architecture, this application is composed of a server and a client. The server will reserve a port number. Then it will listen to any upcoming client. The client then will attempt to connect to the server. When the connection succeeds, it will be possible to exchange text messages. When finished, the connection will be closed.

Using the code

To use sockets in .NET applications, we have to add the following using statements:

using System.Net; 
using System.Net.Sockets; 

Now we can create a socket object:

Socket sListener;    

Programming the server

Let's create a click event that will enable the created socket to set its IpEndPoint and the protocol type.

But before that, a socket needs permission to work, because it will use a closed port number. A window will appear demanding permission to allow sending data.

permission = new SocketPermission(NetworkAccess.Accept, 
                   TransportType.Tcp, "", SocketPermission.AllPorts);

As sockets use a network to transmit data, it uses protocols. The most known in this context are UDP which is fast but not reliable, and TCP which is reliable but not fast. Reliability is recommended when sending messages. That's why I use TCP.

sListener = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 

The socket needs to have an address. It's of type IpEndPoint. Each socket is identified through the IP address, which is useful to locate the host's machine, and the port number to identify which program is using the socket inside the machine.

IPHostEntry ipHost = Dns.GetHostEntry(""); 
IPAddress ipAddr = ipHost.AddressList[0]; 
ipEndPoint = new IPEndPoint(ipAddr, 4510);  

Now we will associate our socket with the IpEndPoint:


So that our socket is ready to use, let's start listening on the chosen port number (4510). You can choose another port number. But the client has to be aware about that. Listening will be handled through this button's event:

Place a socket in a listening state and specify how many client sockets could connect to it:


The server will begin an asynchronous operation to accept an attempt. One of the powerful features of sockets is the use of the asynchronous programming model. Thanks to it, our program can continue running while the socket is performing actions.

AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
sListener.BeginAccept(aCallback, sListener); 

If there is any attempt from the client to connect, the following code will be executed:

Socket listener = (Socket)ar.AsyncState; 
Socket handler  = listener.EndAccept(ar);  

To begin to asynchronously receive data, we need an array of type Byte for the received data, the zero-based position in the buffer, and the number of bytes to receive.

handler.BeginReceive(buffer, 0, buffer.Length, 
          SocketFlags.None, new AsyncCallback(ReceiveCallback), obj); 

If the client sends any message, the server will try to get it. As sockets send data in binary type, converting  them to string type is necessary. It's good to know also that the server, and even the client, don't know anything about the length of the message or the time needed for listening to all of it. That's why we use a special string "<Client Quit>" to put in the end of the message to tell that the text message ends there. To receive data, BeginReceive is called:

byte[] buffernew = new byte[1024];
obj[0] = buffernew;
obj[1] = handler;
handler.BeginReceive(buffernew, 0, buffernew.Length, 
        SocketFlags.None, new AsyncCallback(ReceiveCallback), obj);  

After receiving the client's messages, the server may want to reply. But it has to convert the string message in str to bytes data, because sockets manipulate bytes only.

byte[] byteData = Encoding.Unicode.GetBytes(str);  

The server now will send data asynchronously to the connected socket:

handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler); 

When using the asynchronous programming model to build this sample, there's no risk of application or interface blocking. It will seem like we are using multiple threads.

After writing code, you want to handle the different methods through a user interface. So you may have a UI like this:

Programming the client

The client will try to connect to the server. But it has to know its address.

After creating a SocketPermission for socket access restrictions and creating a socket with a matching IpEndPoint, we have to establish a connection to the remote server host:


We have to note here that the created IpEndPoint will not be used to identify the client. But it'll be used to identify the server socket.

To send messages, the client adds "<Client Quit>" to mark the end of message and must transform the text message to binary format, as the server did. After that, the socket will send the message by invoking the method Send which will take the binary message as a parameter.

byte[] msg = Encoding.Unicode.GetBytes(theMessageToSend + "<Client Quit>"); 
int bytesSend = senderSock.Send(msg);    

For receiving data from the server, it converts the byte array to string and continues to read the data till data isn't available:

String theMessageToReceive = Encoding.Unicode.GetString(bytes, 0, bytesRec);
while (senderSock.Available > 0)
  bytesRec = senderSock.Receive(bytes);
  theMessageToReceive += Encoding.Unicode.GetString(bytes, 0, bytesRec);

To close the connection, we should use Socket.Shutdown(SocketShutdown.Both) and Socket.Close().

After matching events with button's click, the client side user interface will look like this:


I provided here an application that is a sample to use and easy to integrate in your projects. So give yourself a chance to try taking benefit of socket's features to build a more rich and powerful software.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Houssem Dellai
Software Developer
Tunisia Tunisia
Software Engineerwho likes spending my free time developing open source .NET applications.
Mail :
Phone : +216 29 903 563

You may also be interested in...

Comments and Discussions

QuestionI see this is IPv6. How do I convert this from IPv6 to IPv4? Pin
ralpitto15-May-16 5:08
memberralpitto15-May-16 5:08 
AnswerRe: I see this is IPv6. How do I convert this from IPv6 to IPv4? Pin
WJasonM12-Jul-16 4:04
memberWJasonM12-Jul-16 4:04 
QuestionSocket Receive Pin
zcshsh15-Mar-16 18:01
memberzcshsh15-Mar-16 18:01 
Questionsocket Pin
Member 122468215-Jan-16 21:21
memberMember 122468215-Jan-16 21:21 
Questionask for source code Pin
Member 118541854-Aug-15 20:34
memberMember 118541854-Aug-15 20:34 
QuestionGet a beacon Pin
jenya712-Mar-15 0:24
memberjenya712-Mar-15 0:24 
QuestionComment on this article Pin
Member 1024876814-Jul-14 2:06
memberMember 1024876814-Jul-14 2:06 
AnswerRe: Comment on this article Pin
Houssem_Dellai14-Jul-14 8:26
memberHoussem_Dellai14-Jul-14 8:26 
Questionsource code Pin
behnam haji8-Jul-14 22:09
memberbehnam haji8-Jul-14 22:09 
QuestionClient in Windows, Server in Linux Pin
Thomhert Suprapto Siadari18-Aug-13 17:41
memberThomhert Suprapto Siadari18-Aug-13 17:41 
QuestionClient stand by mode. Pin
Meryem gömeç17-Jun-13 23:18
memberMeryem gömeç17-Jun-13 23:18 
GeneralMy vote of 5 Pin
Cornelius Henning1-Jun-13 2:30
memberCornelius Henning1-Jun-13 2:30 
GeneralAwesome article Pin
Barun Kumar Jha29-May-13 14:30
memberBarun Kumar Jha29-May-13 14:30 
QuestionMultiple messages Pin
zanatos12-Apr-13 6:41
memberzanatos12-Apr-13 6:41 
AnswerRe: Multiple messages Pin
Houssem_Dellai13-Apr-13 0:55
memberHoussem_Dellai13-Apr-13 0:55 
GeneralRe: Multiple messages Pin
zanatos14-Apr-13 7:19
memberzanatos14-Apr-13 7:19 
GeneralRe: Multiple messages Pin
Houssem_Dellai14-Apr-13 8:28
memberHoussem_Dellai14-Apr-13 8:28 
GeneralMy vote of 5 Pin
csharpbd3-Dec-12 1:53
membercsharpbd3-Dec-12 1:53 
GeneralMy vote of 4 Pin
Al-Samman Mahmoud2-Dec-12 2:19
memberAl-Samman Mahmoud2-Dec-12 2:19 
GeneralRe: My vote of 4 Pin
Houssem Dellai2-Dec-12 6:13
memberHoussem Dellai2-Dec-12 6:13 
GeneralA good intro Pin
pt14011-Dec-12 20:41
memberpt14011-Dec-12 20:41 
GeneralRe: A good intro Pin
Dellai Houssem1-Dec-12 23:21
memberDellai Houssem1-Dec-12 23:21 
GeneralRe: A good intro Pin
pt14011-Dec-12 23:33
memberpt14011-Dec-12 23:33 
QuestionA good article. Pin
PHS2411-Dec-12 0:06
memberPHS2411-Dec-12 0:06 
AnswerRe: A good article. Pin
Houssem Dellai1-Dec-12 3:30
memberHoussem Dellai1-Dec-12 3:30 
GeneralMy vote of 5 Pin
davide-pro-99917-Oct-12 7:48
memberdavide-pro-99917-Oct-12 7:48 
SuggestionSuggested Reading Pin
Nick Hounsome24-Sep-12 22:04
memberNick Hounsome24-Sep-12 22:04 
GeneralRe: Suggested Reading Pin
Houssem Dellai25-Sep-12 7:26
memberHoussem Dellai25-Sep-12 7:26 
GeneralRe: Suggested Reading Pin
Igor Ladnik2-Jun-13 1:08
memberIgor Ladnik2-Jun-13 1:08 
GeneralMy vote of 5 Pin
Unque24-Sep-12 17:21
memberUnque24-Sep-12 17:21 
Question[My vote of 2] Does not handle network splitting and joining Pin
Nick Hounsome24-Sep-12 3:49
memberNick Hounsome24-Sep-12 3:49 
This has the bug common to a huge number of TCP programs. Fortunately (or unfortunately depending on your view point) it will almost always work for trivial demos especially if run on a single machine or a LAN but if sending sizable or rapid messages over a WAN or any messages to a heavily loaded receiver it will run into the problem that the number of bytes sent in a call to "Send" by a client bears no defined relationship whatsoever to the number received in each call to "Receive" by the receiver.
The code partially acknowledges this with the looping call in the client but it is still wrong on a number of counts:

1) The client send can be split over several packets AND NEED NOT BE SPLIT ON AN EVEN BYTE BOUNDARY. When we consider that we are sending UTF16 (Unicode encoding) we must consider that we might receive only the first half of a character. In this case the decode routine will throw an exception.

2) !socket.Available only tells you that no more data is available now NOT that there never will be any more data.

Bomb proof TCP programming is hard. Using asynchronous I/O as well is VERY hard to get right.

In practice the only good way to handle TCP streams is to have messages with a well defined header containing a length. You should then read bytes until you have at least a header full; calculate how many more you need given the length and then keep reading until you have accumulated the entire message into a buffer. Only then should you analyze the message itself.

It is possible to make some simplifications in the client if the stream is closed by the sender as in this case the end of stream (signified by reading 0 bytes) can be used in place of a length but the multi-byte char problem still stands.

The program as it stands makes no real use of TCP and would probably be better implemented in UDP where Send and Receive match 1 to 1.
AnswerRe: [My vote of 2] Does not handle network splitting and joining Pin
Houssem Dellai24-Sep-12 20:27
memberHoussem Dellai24-Sep-12 20:27 
GeneralRe: [My vote of 2] Does not handle network splitting and joining Pin
Nick Hounsome24-Sep-12 21:48
memberNick Hounsome24-Sep-12 21:48 
GeneralMy vote of 1 Pin
Nick Hounsome24-Sep-12 3:27
memberNick Hounsome24-Sep-12 3:27 
GeneralRe: My vote of 1 Pin
Houssem Dellai24-Sep-12 20:00
memberHoussem Dellai24-Sep-12 20:00 
GeneralRe: My vote of 1 Pin
Nick Hounsome24-Sep-12 21:30
memberNick Hounsome24-Sep-12 21:30 
GeneralRe: My vote of 1 Pin
Houssem Dellai26-Sep-12 7:26
memberHoussem Dellai26-Sep-12 7:26 
QuestionWhat I like Pin
FatCatProgrammer23-Sep-12 9:40
memberFatCatProgrammer23-Sep-12 9:40 
AnswerRe: What I like Pin
Houssem Dellai23-Sep-12 19:59
memberHoussem Dellai23-Sep-12 19:59 
QuestionThanks Pin
EgoDust23-Sep-12 9:05
memberEgoDust23-Sep-12 9:05 
AnswerRe: Thanks Pin
Houssem Dellai23-Sep-12 20:01
memberHoussem Dellai23-Sep-12 20:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171114.1 | Last Updated 31 May 2013
Article Copyright 2012 by Houssem Dellai
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid