我有一些代码:
protected TcpListener ClientListener;
protected TcpClient ClientSocket;
protected Thread th1;
public static string server_ip = string.Empty;
public static string server_port = string.Empty;
internal void start_potok()
{
Protection.Ban.ban_del();
th1 = new Thread(start_listener);
th1.IsBackground = true;
th1.Start();
}
internal void stop_potok()
{
th1.Abort();
if (ClientSocket != null)
{
ClientSocket.Close();
}
ClientListener.Stop();
}
private void start_listener()
{
try
{
ClientListener = new TcpListener(IPAddress.Parse(server_ip), Convert.ToInt32(server_port));
ClientListener.Start();
ClientSocket = default(TcpClient);
while (true)
{
ClientSocket = ClientListener.AcceptTcpClient();
client_connected(ClientSocket);
}
catch (ThreadAbortException ex)
{
//not catch this exception
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
private void client_connected(TcpClient client)
{
//check bans and other
LoginClientProc lcp = new LoginClientProc(client);
}
听取的类:
class LoginClientProc
{
internal EndPoint address;
internal TcpClient client;
internal NetworkStream stream;
private byte[] buffer;
internal LoginClientProc(TcpClient Client)
{
address = Client.Client.RemoteEndPoint;
client = Client;
stream = Client.GetStream();
new System.Threading.Thread(read).Start();
}
void read()
{
try
{
buffer = new byte[2];
stream.BeginRead(buffer, 0, 2, new AsyncCallback(OnReceiveCallbackStatic), null);
}
catch (Exception ex)
{
throw ex;
}
}
private void OnReceiveCallbackStatic(IAsyncResult result)
{
int rs = 0;
try
{
rs = stream.EndRead(result);
if (rs > 0)
{
short Length = BitConverter.ToInt16(buffer, 0);
buffer = new byte[Length - 2];
stream.BeginRead(buffer, 0, Length - 2, new AsyncCallback(OnReceiveCallback), result.AsyncState);
}
else
//0 = client close connection
}
catch (Exception s)
{
}
}
private void OnReceiveCallback(IAsyncResult result)
{
stream.EndRead(result);
byte[] buff = new byte[buffer.Length];
buffer.CopyTo(buff, 0);
if (!verify_packet)
{
//Exception
}
else
{
handle(buff);
new System.Threading.Thread(read).Start();
}
}
private void handle(byte[] buff)
{
byte id = buff[0];
switch (id)
{
//cases for headers packets
default:
//unknown packet
//Here need correct Close connection
break;
}
//response for packet
}
所以,我有一些问题:
- 如何限制客户端连接数量?(例如不超过10个用户)
- 如何限制客户端连接的时间(生命周期)?(例如不超过30秒)
- 如何正确停止监听线程(TcpListener、TcpClient),当应用程序关闭时?
- 当服务器收到未知数据包时,如何正确关闭TcpClient?
感谢您的回答!
TCPListener.Start(Int32)
只是限制了挂起连接的数量,而不是活动连接的数量。请参阅 http://msdn.microsoft.com/en-us/library/5kh8wf6s(v=vs.110).aspx - Rodrick Chapman