看到图片中的问题。服务器启动一个新的任务来接受客户端,然后在Handle(client)函数中对其进行处理,一切正常,但是每次它重复此消息“客户端正在连接...”时,它就可以正常工作,但是不可以。除此消息外,没有其他任务被调用。而且bool Pending()是false,因此它不应该启动另一个Task。
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WebServer
{
class WebServer
{
public static WebServer Server { get; private set; }
private TcpListener _tcpListener = null;
public CancellationTokenSource TokenSource { get; private set; }
public CancellationToken Token { get; private set; }
public int i = 0;
static void Main(string[] args)
{
WebServer.Server = new WebServer();
}
WebServer()
{
IPAddress ipAddress;
try
{
ipAddress = IPAddress.Parse("127.0.0.1");
} catch(Exception e)
{
Console.WriteLine("Error while parsing ip address: " + e.Message);
return;
}
_tcpListener = new TcpListener(ipAddress, 8080);
_tcpListener.Start();
TokenSource = new CancellationTokenSource();
Token = TokenSource.Token;
//Execute server
Task.Run(() => Run());
Console.ReadKey();
TokenSource.Cancel();
WaitHandle handle = Token.WaitHandle;
handle.WaitOne();
}
private void Run()
{
Console.WriteLine("Server is runnning");
while(!Token.IsCancellationRequested)
{
if(_tcpListener.Pending())
{
Console.WriteLine("Pending: " + _tcpListener.Pending());
Task.Run(() => {
Console.WriteLine("Client connecting...");
TcpClient client = _tcpListener.AcceptTcpClient();
this.Handle(client);
return;
});
}
}
}
private void Handle(TcpClient client)
{
NetworkStream stream = client.GetStream();
Console.WriteLine("Handling....");
while(client.Connected)
{
if(stream.DataAvailable)
{
Console.WriteLine("Start Reading...");
byte[] buffer = new byte[1024];
stream.Read(buffer, 0, 1024);
Console.WriteLine("Read: " + Encoding.ASCII.GetString(buffer));
}
client.Close();
}
}
}
}
客户端连接不应每次都重复,其他一切正常
答案 0 :(得分:1)
EmrahSüngü的评论看似准确正确
TcpClient client = _tcpListener.AcceptTcpClient(); // accept first
Console.WriteLine("Client connecting...");
// then start processing in your task
Task.Run(() => this.Handle(client));
考虑到它,处于while循环中,并且要在代码实际运行到客户端之前运行之前,您要启动几个任务。
免责声明 :这是未经测试的,对于由此代码对他人或您自己造成的伤害,我不承担任何责任:)