.NET TcpSocket Programming

What is the correct way to accept sockets in a multi-connection environment in .NET? Will it be enough, even if the load is high?

while (true) { //block untill socket accepted var socket = tcpListener.AcceptSocket(); DoStuff(socket) //eg spawn thread and read data } 

That is, I can accept sockets in one thread, and then process the sockets in the stream / data stream / independently. Thus, the question is only in the receiving part.

+4
source share
7 answers

Since I use Async CTP and DataFlow, the current code is as follows:

 private async void WaitForSockets() { var socket = await tcpListener.AcceptSocketAsync(); WaitForSockets(); incomingSockets.Post(socket); } 

Please note that what looks like a recursive call will not overflow or lock the stack. It will simply launch a new awaiter for the new socket and exit.

0
source

You will most likely need an async BeginAccept operation instead of a synchronous Accept.

And if you want to handle high load, you definitely don't need a thread for each connection - again, you use async methods.

+1
source

Take a look at Reactor or Proactor depending on whether you want to block or not. I recommend Templates for parallel and network objects .

+1
source

This should be fine, but if the load gets even higher, you can use asynchronous versions of this method: BeginAcceptSocket / EndAcceptSocket .

0
source

BeginAcceptSocket is the best choice if you need the most powerful server.

More importantly, these asynchronous operations use Threadpool under the hood, while in your current implementation you create and destroy many threads that are really expensive.

0
source

I think the best approach is to call BeginAccept (), and inside OnAccept, call BeginAccept again. This should give you the best concurrency.

OnAccept should be something like this:

 private void OnAccept(IAsyncResult ar) { bool beginAcceptCalled = false; try { //start the listener again _listener.BeginAcceptSocket(OnAccept, null); beginAcceptCalled = true; Socket socket = _listener.EndAcceptSocket(ar); //do something with the socket.. } catch (Exception ex) { if (!beginAcceptCalled) { //try listening to connections again _listener.BeginAcceptSocket(OnAccept, null); } } } 
0
source

This is actually not very important. What matters is how you communicate with each client. This processing will consume a lot more CPU than receiving sockets.

I would use BeginAccept / EndAccept for a listener socket and BeginReceive / EndReceive for client sockets.

0
source

All Articles