socket queue problem?
I'm a dotnet propgrammer. recently i wrote aclient server application that use system.net.sockets for connecting and check client is on with a timer that clients send byte.minvalue for checking alive. when a client disconnected i shutdown the socket and c开发者_开发技巧lose it. this work fine, but when number of clients increased connections can't established and problem occured. I use backlog with 2000 value but don't work correctly? Help Me!
That's pretty vague, some more detail (the errors that you're getting on the client, and/or the server) or some code (how you're accepting connections on the server?) might help.
In the meantime, I'll throw some random guesses at you...
If you're creating and destroying connections from your clients quickly and you're testing your server by running lots of clients on the same machine then you may be suffering from running out of sockets due to TIME_WAIT
. Likewise if you're testing your server by creating lots of client connections (generally more than 4000) from the same windows machine then you may be running into the default MAX_USER_PORT
setting which severely limits the number of concurrent outbound connections that you can make at one time.
Why are you locking when calling OnClientAccept? It's a bottle neck.
If you need a lock, do it more finegrained inside OnClientAccept.
Also. Switch to BeginAccept/EndAccept to increase speed.
internal class SocketServer
{
private readonly IPAddress _address;
private readonly int _port;
private TcpListener _listener;
public SocketServer(IPAddress address, int port)
{
_address = address;
_port = port;
}
public void Start(int backlog)
{
if (_listener != null)
return;
_listener = new TcpListener(_address, _port);
_listener.Start(backlog);
_listener.BeginAcceptSocket(OnAccept, null);
}
private void OnAccept(IAsyncResult ar)
{
TcpClient client = null;
try
{
client = _listener.EndAcceptTcpClient(ar);
}
catch(Exception err)
{
// log here. Eat all exceptions so the server will not die.
// i usually have a ExceptionThrown event to let other code
// debug asynchrounous exceptions.
}
// Begin to accept clients asap
try
{
_listener.BeginAcceptTcpClient(OnAccept, null);
}
catch(Exception)
{
// read above exception comment.
}
// this accept failed, lets not do anything with the client.
if (client == null)
return;
try
{
OnClientAccepted(client);
}
catch(Exception)
{
// read above exception comment.
}
}
private void OnClientAccepted(TcpClient client)
{
throw new NotImplementedException();
}
}
How quickly are clients connecting/disconnecting? TCP sockets don't close immediately, they go into a TIME_WAIT state and hang around for a while (I think the default on Windows is 120secs). This may lead to all sockets being in use and new connections refused.
MSDN info here: http://msdn.microsoft.com/en-us/library/ms819739.aspx
On the server type:
netstat -a
If you have a large number of TIME_WAIT connections then you need to reduce the time closed sockets hang about.
精彩评论