Socket programming in C#

Hi All.

I have just recently learnt how to do socket programming in C#. I know how to do both synchronous and asynchronous sockets. Problem is I'm not sure how to accept multiple clients. There is code in the constructor of my main program to start listening on a specified port. Once a client connects to that port, the socket now handles that client only. Right?
I should create an event that creates a new socket every time the listening one gets connected to a client. And another event when a client disconnects.Right?

Any advice on how to implement this? Or any links to resources that I should read?

Thanks in advance.


  • its better to start the listening for new clients in another method rather than in constructor. Constructor has the defination to perform initialization for the objects ... so better let it do that.

    The rest of the implementation is very simple. All you have to do is to put your server to listen in a "while (true)" or "while (ConnectedClients <= MAXIMUM_CLIENTS) loop. Now in the AsyncCallback of BeginAccept() Perform the adding of that client in an array or ArrayList of Sockets or Objects or whatevery data type you like. Everytime a asynchoronous function ends while calling back its AsyncCallback funtion, an event (ManualResetEvent) should be fired like

    ManualResetEvent AcceptClientEvent = new ManualResetEvent(false);

    void func ()
    SocketList[ClientCounter] = (Socket)AsyncObject.EndAccept();


    void CallingFunc()
    Socket Client = Listener.BeginAccept(
    new AsyncCallback(Callback_Accept),Listener);

    I hope this will help you out.

    FaraZ H.
  • Thanks FaraZ for the reply.

    I've noticed that MSDN uses a similar approach in their sample code. One thing that puzzles me, is why you would want to use the [code]AcceptClientEvent.WaitOne(); [/code] method. The way I understand it, this method causes the current thread to block until another thread signals it. Is this not exactly what a synchronous socket would do? (Such as when you call mySocket.Accept()). Anyways I found a solution to my problem at this site.
    It basically starts a new thread and gives that thread the responsabilty of accepting socket connections.

    Thanks again for your help

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


In this Discussion