问题
I have a service which as it's coming up invokes the Start() method on a TcpListener instance. This listener is using a port that is not common and not known to be used by any other services. Very very rarely for a span of minute or so it experiences an odd error. For a minute the service (which on failure restarts immediately) back to back crashes on the following exception:
SocketException
at System.Net.Sockets.Socket.DoBind(System.Net.EndPoint, System.Net.SocketAddress)
at System.Net.Sockets.Socket.Bind(System.Net.EndPoint)
at System.Net.Sockets.TcpListener.Start(Int32)
at MyTestServer.Server.StartListening()
With exception message as follows:
Only one usage of each socket address (protocol/network address/port) is normally permitted
This article suggests that I'm experience port exhaustion and that I should tweak the registry to modify timeout and port range values for WinSock. This is all good and well, but I only have (or expect to have) 50-100 clients connecting. How could I possibly run out of ports? Bots and port scanners?
回答1:
It probably isn't port exhaustion as it was in that post. They were connecting out with WCF (which would be like the TCPClient). You are binding to a TCP Port and waiting for the connection. It isn't strictly the same thing. You are binding to a specific TCP Port number. When you get this message, windows (correctly or not) thinks that it is in use. Windows is reporting that another process is already bound to that port, so you can't. You can have 2 processes trying to use the port and get this problem, so the 50-100 figure isn't the issue.
Either you are causing this problem somewhere else or there is some other application that is causing this problem.
If the service is experiencing a problem and dies without ever calling TCPListener.Stop(), then the service restarts itself, it won't be able to bind to the port because windows may not know the process is done with it.
You'll have to post more details to get into it any further.
来源:https://stackoverflow.com/questions/10883639/c-sharp-tcplistener-start-causing-socketexception-with-message-only-one-us