我正在使用一个套接字服务器程序,该程序同时接受超过1000个客户端。很少有东西
几乎没有问题......
如何在不断开连接的情况下从客户端接收数据(除非客户端断开连接)?
我也在更新文件中连接的客户端。似乎没有客户总是在增加(一些时间也在减少,但增长率要高得多)。如何使连接的客户端更准确?
这是代码......
public static ManualResetEvent allDone = new ManualResetEvent(false);
// private static DataTable dtServiceId = General.GetAllServiceID();
private static int numconnections;
private static int disconnected;
public static void StartListening()
{
IPEndPoint ipEndPoint = new IPEndPoint(Dns.Resolve(Dns.GetHostName()).AddressList[0], GlobalVariable.ListenPort);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind((EndPoint)ipEndPoint);
listener.Listen((int)SocketOptionName.MaxConnections);
while (true)
{
allDone.Reset();
try
{
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
}
catch (Exception ex)
{
}
allDone.WaitOne();
}
}
catch (Exception ex)
{
}
}
public static void AcceptCallback(IAsyncResult ar)
{
try
{
allDone.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = ((Socket)ar.AsyncState).EndAccept(ar);
Interlocked.Increment(ref numconnections);
// Writing no of clients in a file
StateObject stateObject = new StateObject();
stateObject.workSocket = handler;
handler.BeginReceive(stateObject.buffer, 0,stateObject.buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), stateObject);
}
catch (Exception ex)
{
}
}
public static void ReadCallback(IAsyncResult ar)
{
string content="";
StateObject stateObject = (StateObject)ar.AsyncState;
Socket handler = stateObject.workSocket;
try
{
int count = handler.EndReceive(ar);
if (!handler.Connected || count<=0)
{
CloseConnection(handler);
return;
}
stateObject.sb.Append(Encoding.ASCII.GetString(stateObject.buffer, 0, count));
content = (stateObject.sb).ToString().Trim();
stateObject.sb.Clear();
if (content != "")
{
// Doing data insertion
}
handler.BeginReceive(stateObject.buffer, 0, stateObject.buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), stateObject);
}
catch (SocketException se)
{
CloseConnection(handler);
}
catch (Exception ex)
{
CloseConnection(handler);
}
}
private static void CloseConnection(Socket handler)
{
Interlocked.Decrement(ref numconnections);
Interlocked.Increment(ref disconnected);
// Writing no of clients in a file
handler.Dispose();
}