我一直在为我的应用程序编写服务器 . 由于建议,我决定使用 HttpListener
来监听 async
方法中的传入连接 . 我目前的代码如下:
public static async void StartServerAsync()
{
while (true)
{
Console.WriteLine("Waiting for client.. ");
var context = await listener.GetContextAsync();
Console.WriteLine("Client connected!");
// ReSharper disable once CSharpWarnings::CS4014
Task.Factory.StartNew(() => ProcessClient(context));
}
listener.Close();
}
这个方法是这样开始的:
public static void ServerBoot()
{
listener.Prefixes.Add("http://localhost:1000/");
listener.Start();
StartServerAsync();
}
ProcessClient()
方法如下:
private static void ProcessClient(HttpListenerContext context)
{
try
{
var request = context.Request;
string response;
using (var reader = new StreamReader(request.InputStream, request.ContentEncoding))
{
response = reader.ReadToEnd();
}
Console.WriteLine("Got command: {0}", response);
}
catch (WebException)
{
Console.WriteLine("Error reading string, closing..");
return;
}
}
现在它只应该发布字符串 . 但是,当我使用此代码运行客户端时:
Console.WriteLine(" -- Bagrut Client -- ");
Console.Write("Enter IP of server to connect to: ");
// ReSharper disable once AssignNullToNotNullAttribute
var ip = Console.ReadLine();
WebClient client = new WebClient();
var response = client.UploadString(ip, "query");
Console.WriteLine("Type of response is {0}", response);
服务器什么都不做 . 正如您在 ProcessClient()
中看到的那样,在服务器循环本身中,它至少应该在客户端连接时说出一些内容 . 但是,当代码运行时,没有任何反应 . 难道我做错了什么?
编辑:新代码:
public static void ServerBoot()
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:1337/");
listener.Start();
StartServerAsync(listener).ContinueWith(task => { });
}
private static void ProcessClient(HttpListenerContext context)
{
try
{
var request = context.Request;
string response;
using (var reader = new StreamReader(request.InputStream, request.ContentEncoding))
{
response = reader.ReadToEnd();
}
Console.WriteLine("Got command: {0}", response);
}
catch (WebException)
{
Console.WriteLine("Error reading string, closing..");
return;
}
}
private static async Task StartServerAsync(HttpListener listener)
{
while (true)
{
Console.WriteLine("Waiting for client.. ");
var context = await listener.GetContextAsync();
Console.WriteLine("Client connected!");
// ReSharper disable once CSharpWarnings::CS4014
Task.Factory.StartNew(() => StartServerAsync(listener));
ProcessClient(context);
await StartServerAsync(listener);
}
listener.Close();
}