I have a code:
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)
{
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
private void client_connected(TcpClient client)
{
LoginClientProc lcp = new LoginClientProc(client);
}
Listening Class:
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
}
catch (Exception s)
{
}
}
private void OnReceiveCallback(IAsyncResult result)
{
stream.EndRead(result);
byte[] buff = new byte[buffer.Length];
buffer.CopyTo(buff, 0);
if (!verify_packet)
{
}
else
{
handle(buff);
new System.Threading.Thread(read).Start();
}
}
private void handle(byte[] buff)
{
byte id = buff[0];
switch (id)
{
default:
break;
}
}
So, I have a few questions:
- How to limit the number of client connections? (no more than 10 users, for example)
- How to limit the time (life) of client connections? (e.g. no more than 30 seconds)
- How to stop listening to threads (TcpListener, TcpClient), as when closing the application?
- How to close TcpClient correctly when the server received an unknown packet?
Thanks for your answers!
source
share