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?
Ususally for multi connection application the server listens to a specific port, and after recieving a connection it return a new port where your device will create a new socket.
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.
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.