我正在尝试使用async / await使用异步服务器制作一个非常简单的客户端-服务器应用程序。我在解决方案中有2个项目:
服务器是控制台应用程序。服务器代码:
class Program
{
static async void Run()
{
TcpListener listener = new TcpListener(IPAddress.Loopback, 5000);
listener.Start();
Console.WriteLine("Server is running...");
Console.WriteLine("Server is listening on port 5000...");
while (true)
{
Console.WriteLine("Waiting for client...");
Socket s = await listener.AcceptSocketAsync();
//Socket s = listener.AcceptSocket();
Console.WriteLine("Socket accepted.");
}
}
static void Main(string[] args)
{
Run();
}
}
客户端是Windows窗体应用程序。客户代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(new IPEndPoint(IPAddress.Loopback, 5000));
}
}
当我运行两个项目并单击按钮时,我得到System.Net.Sockets.SocketException(无法建立连接,因为目标计算机主动拒绝了它)。
同步服务器工作正常:
//Socket s = await listener.AcceptSocketAsync();
Socket s = listener.AcceptSocket();
我已经搜寻了两天,但没有找到任何可以帮助的东西。我究竟做错了什么?
谢谢您的回答。
在控制台应用程序中,当您运行此程序时,该应用程序实际上将立即关闭。您需要调用.Wait()
onRun
方法来防止这种情况:
static void Main(string[] args)
{
Run().Wait();
}
此外,您的Run
方法应定义如下(Task
返回):
static async Task Run()
{
// Omitted for brevity...
}
否则,就是一劳永逸。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句