How to C# Socket Programming using Visual Studio.Net

Learn step by step network programming using C#.Net socket, remoting, WCF and SignalR technology from lots of source code and description. All source code download link available at end of the blog post.

Server Socket Programming in C#, how to start

For beginner socket is quite complicated. But it's not very hard to learn. Basically I've learned it within few hours. So I believe it can learn any body. However let's start.

Socket programming have two part
I. Server
II. Client.

I. Server:
To start server need to follow some steps, these are:
i. First create a IPEndPoint
[e.g. IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, port);]

ii. Create a socket object.
[Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);]

iii. Bind socket with IPEndPoint.
[sock.Bind(ipEnd);]

iv. Place socket in Listen mode (to accept call of client)
[sock.Listen(maxClientReceived);]

v. When any call comes from client Accept that call.
[Socket clientSock = sock.Accept();]
At that position Accept() return a new socket to continue communication with called client. By that socket Client-Server communication continue.

To send some data (in byte array form) to client from server just write
clientSock.send(byteArrayData);

To receive client data just write
int receivedLen= clientSock.Receive(clientData);
Receive() function reads data in byte array form from client socket and writes to 'clientData' array, and return integer value how much bytes has received.

I'm giving complete code of a simple server socket below:-


using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace beginSocketServer
{
class Program
{
static void Main(string[] args)
{
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 5656);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
sock.Listen(100);
Socket clientSock = sock.Accept();
byte[] clientData = new byte[1024];
int receivedBytesLen = clientSock.Receive(clientData);
string clientDataInString = Encoding.ASCII.GetString(clientData, 0, receivedBytesLen);
Console.WriteLine("Received Data {0}", clientDataInString);
string clientStr = "Client Data Received";
byte[] sendData = new byte[1024];
sendData= Encoding.ASCII.GetBytes(clientStr);
clientSock.Send(sendData);
clientSock.Close();
Console.ReadLine();
}
}
}


To run that server code you don't need to write client code just open a webbrowser and write (I've use Mozilla Firefox 2.0.0.7) :
http://localhost:5656/

Server console output was:

Received Data GET / HTTP/1.1Host: localhost:5656User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,
*/*;q=0.5Accept-Language: en-us,en;q=0.5Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7Keep-Alive: 300Connection: keep-alive

And in web browser output was:Client Data Received.

Ok, Simple server socket application has done. Next will give simple client socket application for beginner.


see more

Labels: , , , , , , ,

  1. Blogger Sumanta Pramanick | October 4, 2007 at 7:07 PM |  

    Nice and Help full information, please provide something more details.

  2. Blogger joshy | October 29, 2007 at 10:54 PM |  

    Hi While went through caught this blogs...however great effort...

    Joshy
    kuwait

  3. Blogger joshy | October 29, 2007 at 11:45 PM |  

    hi if u dont mind , pls tell me how i can compile above program . Do i need to create class library types or Console Application type.
    if the case first how i will compile ? thanks.

    Joshy

  4. Blogger Suman Biswas | October 29, 2007 at 11:56 PM |  

    Hi Joshy,
    Thanks for your reply. These codes are completely ready made. You just create a console application then remove all codes from there and just copy and paste all code (any of article), then built and run or directly run it.
    Hope your requirement will be solved.
    Thanks again, please reply about your experiance.
    Suman Biswas, India

  5. Blogger Jagadish Manna | November 1, 2007 at 2:13 PM |  

    This is actually good artical. I think it will be helpful to all particularly who are working on soket programming. I need more artical like these.I wise him best of luck.
    Jaga

  6. Blogger bodat | November 12, 2007 at 6:47 AM |  

    hi tanks for this!!!
    any sample code on voice chat and file transfer?? thanks in advance!!

  7. Blogger bodat | November 12, 2007 at 6:48 AM |  

    hi tanks for this!!!
    any sample code on voice chat and file transfer?? thanks in advance!!

  8. Blogger Suman Biswas | November 12, 2007 at 11:08 AM |  

    Hi Bodat,
    Thanks for reading my blog.
    Very soon I will post new article on File Transfer, please visit my blog in future. And now I'm working on voice chat by C# socket, but still it's not in such stage by that I can write article for audience. In future it will be.
    Thanks again,
    Suman

  9. Blogger bodat | November 12, 2007 at 4:59 PM |  

    thanks in advance!!!
    i have found and enhance code in
    java for voice chat!!! but i cannot
    find one in c#!! please email me if
    you have completed it, thanks!!

  10. Blogger Weng | December 14, 2007 at 8:25 AM |  

    This is very good article but is good if you can provide this server listen to more than one browser...

    Good Jobs.

  11. Blogger SHINOJ | June 6, 2008 at 10:28 PM |  

    hi if u don't mind,pls tell me how to transfer file client to client through server using sockets

  12. Blogger Suman Biswas | June 6, 2008 at 10:40 PM |  

    Hi,
    To transfer data need to connect server-client socket. Now if your client ip can resolved directly ( both side ip can get directly) then you just connect and send data. But if you can't connect directly then problem comes. Generally it happens in internet based application but for lan type communication it can connect easyly. So for internet based application need to help of one dadecated ip. Which will act as Server. So to send data you need to send Sender client->server->Receiver client.
    Hope it will help you.

  13. Blogger Vijay | September 11, 2008 at 3:37 PM |  

    Hi.,
    Have u done any multi client chat application using c#..? i.e one to many chat application..If yes pls send it to my mail..

    ji_vijay@yahoo.co.in

    Thanx in advance..

  14. Blogger Suman Biswas | September 11, 2008 at 5:25 PM |  

    Hi Vijay,
    I've done it. But was using .Net Remoting technology in C#. But I'm sorry because I don't have these code. If you need technical help I can help you. You can search it in codeproject.com.
    Thanks,
    Suman

  15. Blogger Sudheendra | October 17, 2008 at 1:08 PM |  

    hi,
    Nice code this help me lot.

    Thanks
    sudheendra

  16. Blogger subramani | October 20, 2008 at 8:00 PM |  

    hi...i just tried ur socket program...i hve some error in my compilation....i dont know how to clear that... i wrote here the following Program..But i got some Errors..can u help me...(subramanitnj@gmail.com)

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;

    namespace SocketConsole
    {
    class Program
    {
    static void Main(string[] args)
    {
    PEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 5656);
    Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    sock.Bind(ipEnd);
    sock.Listen(100);
    Socket clientSock = sock.Accept();
    byte[] clientData = new byte[1024];
    int receivedBytesLen = clientSock.Receive(clientData);
    string clientDataInString = Encoding.ASCII.GetString(clientData, 0, receivedBytesLen);
    Console.WriteLine("Received Data {0}", clientDataInString);
    string clientStr = "Client Data Received";
    byte[] sendData = new byte[1024];
    sendData = Encoding.ASCII.GetBytes(clientStr);
    clientSock.Send(sendData);
    clientSock.Close();
    Console.ReadLine();
    }
    }
    }


    Error List:
    Error 1 The type or namespace name 'PEndPoint' could not be found (are you missing a using directive or an assembly reference?)
    Error 2 The best overloaded method match for 'System.Net.Sockets.Socket.Bind(System.Net.EndPoint)' has some invalid arguments
    Error 3 Argument '1': cannot convert from 'PEndPoint' to 'System.Net.EndPoint' E:\SocketConsole\SocketConsole\Program.cs 15 23 SocketConsole

  17. Anonymous Anonymous | April 18, 2009 at 7:29 PM |  

    hi...bro please can u tell me.
    how you hyperlinked your content.
    plz mail me at manjeetkumar53@gmail.com

  18. Blogger abhishek | August 31, 2010 at 12:50 AM |  

    This comment has been removed by the author.

  19. Blogger abhishek | August 31, 2010 at 12:55 AM |  

    hey man I think U worked really hard to get all these .
    well actually i was searching for code to send email in lan to any one but certainly found ur blog abt socket programming and its rocking well done keep it up!!!!!!!!!!!!
    hey if u get some time do visit my blog "entity.mywapblog.com". A techno blog hope u will like it.

  20. Blogger Jashanpreet | October 11, 2012 at 4:11 PM |  

    bro , little help when i open using your code
    static void Main(string[] args)
    {
    //while (true)
    //{
    //try
    //{
    IPEndPoint ipend = new IPEndPoint(IPAddress.Any, 5000);//just like tcplistener , creating what and where to listen
    Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);//defining socket
    soc.Bind(ipend);//binding socket to istener
    soc.Listen(100);
    Socket sock = soc.Accept();
    byte[] welcome = new byte[1024];
    welcome = Encoding.ASCII.GetBytes("Welcome to my first server");
    sock.Send(welcome);
    byte[] recieve = new byte[1024];
    // while (!recieve.Equals("x"))
    //{
    int len = sock.Receive(recieve);
    string recieved = Encoding.ASCII.GetString(recieve, 0, len);
    Console.WriteLine("Recieved data: {0}", recieved);
    byte[] ok = new byte[1024];
    ok = Encoding.ASCII.GetBytes("data Recieved");
    sock.Send(ok);
    //}
    sock.Close();
    Console.ReadLine();
    //}
    //catch (Exception e)
    //{
    // Console.WriteLine(e.ToString());
    //}
    //}
    }
    i got an exception on
    sock.send(ok);
    that
    An established connection was aborted by the software in your host machine

    can you help and telll me what i did wrong..its a runtime error

  21. Blogger Jashanpreet | October 11, 2012 at 4:14 PM |  

    hey it worked with mozilla only

leave a response