【问题标题】:TcpListener not accepting clientTcpListener 不接受客户端
【发布时间】:2017-02-18 19:09:02
【问题描述】:

我有一个我尝试使用 TcpListener 创建的 Web 服务器,但它不会接受我发出的大约一半的请求。发出请求时它只是挂在AcceptTcpClient 上,它在任何端口上的行为都相同。

this.main = new Thread(() =>
{
     while (this.running)
     {

         TcpClient c = this.t.AcceptTcpClient();
         new Task(() =>
         {
             handleClient(c);
         }).Start();

     }
});
this.main.Start();

【问题讨论】:

标签: c# tcplistener


【解决方案1】:

也许你可以试试这样的:

public void Start()
{
    Console.WriteLine("Server started...");

    TcpListener listener = new TcpListener(System.Net.IPAddress.Loopback, 1234);
    listener.Start();
    while (true)
    {
        TcpClient client = listener.AcceptTcpClient();
        new Thread(new ThreadStart(() =>
        {
            HandleClient(client);
        })).Start();
    }
}

 private void HandleClient(TcpClient client)
 {
    NetworkStream stream = client.GetStream();
    StreamWriter writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true };
    StreamReader reader = new StreamReader(stream, Encoding.ASCII);

    string inputLine = reader.ReadLine();
    Console.WriteLine("The client with name " + " " + inputLine + " is conected");

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-16
    • 2010-11-15
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多