Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple socket connections

Tags:

c#

.net

sockets

I have multiple devices connected to a TCP/Ip port and i want to read all these devices through sockets in .Net how can i do this before this i had a single device connected and it was working fine but now i have multiple devices can anybody help me in listening multiple socket connection?

like image 342
Mohammad Tanveer Avatar asked Jun 10 '26 03:06

Mohammad Tanveer


2 Answers

This is not a complete answer, but should point you in the right direction. You can use something like
Socket socketForClient = tcpListener.Accept();
call for every connecting client. You can have an array of Socket objects you can process/update as new connections come in or get closed.

like image 189
Belrog Avatar answered Jun 18 '26 01:06

Belrog


You will want to create an asynchronous Tcp listener. Read up here: MSDN Socket Class

First you set up your listener:

private static System.Threading.ManualResetEvent connectDone =
            new System.Threading.ManualResetEvent(false);

void StartListen(IPEndPoint serverEP, int numDevices)
{
    sock.Bind(serverEP);
    sock.Listen(numDevices); // basically sit here and wait for client to request connect

    /*
    * While statement not required here because AcceptConnection()
    * method instructs the socket to BeginAccept()...
    */
    connectDone.Reset();
    sock.BeginAccept(new AsyncCallback(AcceptConnection), sock);
    connectDone.WaitOne();
}

In some examples, you might see the the BeginAccept(...) method inside of a while(true) block. But you don't need that with async. I think using the while(true) is improper. Of course, you then accept connections aynchronously:

void AcceptConnection(IAsyncResult asyncRes)
{
    connectDone.Set();
    System.Net.Sockets.Socket s = channelworker.EndAccept(asyncRes);
    byte[] messagebuffer = new byte[bufferSize];

    /*
     * Tell socket to begin Receiving from caller.
     */
    s.BeginReceive(messageBuffer, 0, messageBuffer.Length,
        System.Net.Sockets.SocketFlags.None, new AsyncCallback(Receive), s);

    /* 
     * Tell Channel to go back to Accepting callers.
     */
    connectDone.Reset();
    sock.BeginAccept(new AsyncCallback(AcceptConnection), sock);
    connectDone.WaitOne();
}

Usually, once you work through a couple of the asynchronous exercises and get the hang of .Beginxxx/.Endxxx methods, and using the AsyncCallback, you will get the hang of how it works. Read through the MSDN reference I gave you and this should get you a pretty good start.

like image 28
IAbstract Avatar answered Jun 18 '26 02:06

IAbstract



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!