Wednesday, December 11, 2013

Basic .Net Socket Class Implementation in C#


The .Net Framework provides a Socket class which has the all properties of TcpClient , TcpListener and UdpClient and plus its own methods. For details of .Net Socket class you can see here. In my previous articles I have shown you the basic implementation of TcpClient, TcpListener and UdpClient class. Here we are going to use the Socket class. Many things are same as previous articles so I like to discuss only Socket class implementation and ignore other things

Downloading the source code

Download complete source code from below:
Client program
Server program

Explaining the source code

Lets start digging the code.
For client program SocketEchoClient
Socket sock = null;

// Create a TCP socket instance

sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

A Socket constructor which specify the address type , socket type and protocol type. Here protocol type is TCP for UDP protocol you have to use "ProtocolType.Udp".

// Creates server IPEndPoint instance. We assume Resolve returns at least one address

IPEndPoint serverEndPoint = new IPEndPoint(Dns.Resolve(server).AddressList[0],;servPort);

// Connect the socket to server on specified port


Connect method takes an IPEndPoint argument which specify the address and port of the server.

// Send the encoded string to the server

sock.Send(byteBuffer, 0, byteBuffer.Length, SocketFlags.None);

Send() Method is used to send the string details you can find here.
sock.Receive(byteBuffer, totalBytesRcvd,byteBuffer.Length - totalBytesRcvd, SocketFlags.None))

Receive() Method is used to receive the string details you can find here.

For server program SocketEchoServer
Socket server = null;

// Create a socket to accept client connections

server = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);

server.Bind(new IPEndPoint(IPAddress.Any, servPort));


Socket Bind() method associate with local address and port number. Listen() method takes an integer argument representing the number of connection allowed to queue.

Running the program

First run the server program in command window.
Then run the client in another command window 
c:\>SocketEchoClient "localhost" "This is echo message"