【问题标题】:Unable to connect to asynchronous server using async/await无法使用 async/await 连接到异步服务器
【发布时间】:2016-07-19 19:26:57
【问题描述】:

我正在尝试使用 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();
    }
}

Client 是一个 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();

我已经搜索了两天,但没有找到任何可以帮助的东西。我做错了什么?

感谢您的回答。

【问题讨论】:

  • 您的服务器可能会立即退出。尝试制作方法签名static async Task Run(),然后在main 方法中等待其结果,如下所示:Run().Wait();
  • @YacoubMassad 这行得通。谢谢。

标签: c# sockets asynchronous async-await


【解决方案1】:

在您的控制台应用程序中,当您运行此应用程序时,该应用程序实际上会立即关闭。您需要在 Run 方法上调用 .Wait() 来防止这种情况:

static void Main(string[] args)
{
    Run().Wait();
}

此外,您的Run 方法应该这样定义(Task 返回):

static async Task Run()
{
    // Omitted for brevity...
}

否则,就是一劳永逸。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-17
    • 2017-05-13
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 2019-10-05
    • 2014-03-16
    • 2013-09-19
    相关资源
    最近更新 更多