我一直在为我的应用程序编写服务器。根据建议,我决定使用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();
}