问题
I am developing open source socket server library: https://sourceforge.net/projects/socketservers/
And I would to like to add socket reuse feature to this lib. I have implement draft of this feature, but I do not see any benefits in my tests. The client makes 32K connect-disconnects by 8 items to the server and measure the time. But here is no difference between reusing socket and not reusing socket - same time elapsed for this test.
What I am doing wrong in test?
What benefit should server get when reuse sockets, and how to measure this benefit?
回答1:
The question is if the OS or the runtime does not perform the reuse automatically when invoking a new socket.
The Socket.Disconnect Method documentation points into this direction:
Closes the socket connection and allows reuse of the socket.So this seem to be an over-optimization.
回答2:
I can explain what happens from an unmanaged point of view and how DisconnectEx()
is used, perhaps someone can then map this to the managed scenario.
In unmanaged code you would use DisconnectEx()
to reuse a socket for an subsequent AcceptEx()
or ConnectEx()
call, more likely the former. So you'd initially create x sockets and post your overlapped async accept operations using AcceptEx()
. When clients connect to these pending connection you would do your server stuff and then at the end call DisconnectEx()
on the socket and post a new AcceptEx()
using that socket. This avoids the need to create a new socket at this point and it's thus more efficient for the server. The performance difference is probably pretty small but worth having on heavily loaded servers that are accepting lots of short lived connections.
So I suggest you post some code showing how you're reusing your socket after calling Disconnect(true)
on it...
回答3:
In case you mean something like SO_REUSEADDR or SO_REUSEPORT:
Socket reuse is essentially important if e.g. your server crashes but there are still connections lingering.
If you restart your server, you'd normally have to wait till the operating system gracefully closed those connections, before you can rebind your socket to that port.
This could mean, that some processes which heavily rely on your server to come to a halt till it has been restarted.
Due to the socket reuse feature, you circumvent this problem.
There might be other uses for this, but I can only think of this one right now. Hope that helped.
来源:https://stackoverflow.com/questions/4133150/what-is-benefit-from-socket-reuse-in-c-sharp