0
我正在創建我的第一個應用程序它的一個小服務器。我只是想知道接受多重連接但不會被淹沒的最佳方式是什麼,例如在10秒內連接10個連接,然後如果淹沒在聽衆附近。線程或線程池會幫助我做到這一點。C#Tcp Listener接受多個連接但不會被淹沒?
我添加了線程池,但不知道我應該如何將它用於我的應用程序。
請看看我的代碼,看看我需要做些什麼才能使它安全並且不會被淹沒。
感謝
class Listener
{
public static TcpListener _listener;
private static TcpClient _client;
private static NetworkStream _clientStream;
public Listener(string ip, Int32 port)
{
ThreadPool.SetMaxThreads(50, 100);
ThreadPool.SetMinThreads(50, 50);
// Set the TcpListener IP & Port.
IPAddress localAddr = IPAddress.Parse(ip);
_listener = new TcpListener(localAddr, port);
}
public void Start() // Run this on a separate thread, as
{ // we did before.
_listener.Start();
Console.WriteLine("Starting server...\n");
Console.WriteLine("Listening on {0}:{1}...", Globals._localIP, Globals._port);
while (Globals._Listen)
{
try
{
if (!_listener.Pending())
{
Thread.Sleep(500); // choose a number (in milliseconds) that makes sense
continue; // skip to next iteration of loop
}
Globals._requestCounter += +1;
// Get client's request and process it for web request.
ProcessRequest();
}
catch (SocketException e)
{
// Listener Error.
}
catch (InvalidOperationException er)
{
}
}
_listener.Stop();
}
public static void Stop()
{
Globals._Listen = false;
}
}
static void Main(string[] args)
{
// Set listener settings.
var server = new Listener(Globals._localIP, Globals._port);
// Start the listener on a parallel thread:
Thread listenerThread = new Thread(server.Start);
listenerThread.Start();
Thread.Sleep(500);
}
這聽起來不錯。你有什麼鏈接的例子或教程我新來c sharp。謝謝 – Joe 2010-08-20 00:26:28
無法擊敗源代碼;) http://msdn.microsoft.com/en-us/library/ms735119(VS.90).aspx 介紹指南: http://msdn.microsoft.com /en-us/netframework/first-steps-with-wcf.aspx 這些示例很棒: http://www.microsoft.com/downloads/details.aspx?FamilyID=35ec8682-d5fd-4bc3-a51a- d8ad115a8792&displaylang = EN – Doobi 2010-08-20 13:52:47