Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polling over thousands of TCP sockets

I need to connect to thousands of clients over TCP on a proprietary protocol to acquire data cyclically. I need to write a .NET server application in C#.

The first attempt was to create for each tcp socket an own thread, which works but needs a lot of cpu usage.

I found out that it would be a better idea to use the .NET threadpool instead. As far as I understand (http://msdn.microsoft.com/en-us/library/ms973903.aspx) I could use timers in order to get each socket acquire the data cyclically in a given period (like 1 sec). This does not work for me because the sockets time out once the connection was openende because there are a lot of more sockets which have to be opened before it's the open sockets turn again.

Another try was using asynchronous callbacks. This would work for me but I don't know how to get the sockets acquire data cyclically???

like image 642
sqeez3r Avatar asked Apr 24 '12 14:04

sqeez3r


People also ask

What is polling in sockets?

The poll() API allows simultaneous connection with all descriptors in the queue on the listening socket. The accept() and recv() APIs are completed when the EWOULDBLOCK is returned. The send() API echoes the data back to the client. The close() API closes any open socket descriptors.

How many sockets does TCP need?

Maximum number of sockets. For most socket interfaces, the maximum number of sockets allowed per each connection between an application and the TCP/IP sockets interface is 65535.

Are socket connections expensive?

Creating socket is cheap. Connecting it actually creates the connection, which is more or less as expensive as creating the underlying connection, specially TCP connection. TCP connection establish requires the three-way TCP handshake steps.

Can you open multiple sockets on a port?

@premktiw: Yes, multiple client sockets can be bound to the same local IP/port pair at the same time, if they are connected to different server IP/Port pairs so the tuples of local+remote pairs are unique.


1 Answers

Try using Socket's high performance API which allows simultaneously receiving data on a very large number of sockets, without using one thread per socket. At the bottom of the article there's a link to a complete sample. There's also a sample in the MSDN article for the SocketAsyncEventArgs class.

like image 167
Allon Guralnek Avatar answered Oct 12 '22 06:10

Allon Guralnek