You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何我的C# UDP聊天程序无法获取键盘输入?

UDP聊天程序无法获取键盘输入的原因及解决办法

问题原因

你的代码中client.Receive(ref remoteEp)是阻塞式方法,程序会一直停在这行代码等待接收UDP消息,只有收到消息后才会继续执行后续的键盘输入逻辑。也就是说,在没有收到任何消息前,程序根本不会走到Console.ReadLine()这一步,自然无法获取键盘输入。

解决办法

要同时处理接收消息和键盘输入,需要把接收逻辑放到单独的线程或异步任务中,让两个操作并行执行。以下是修改后的代码示例:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

class UDPClient
{
    static UdpClient client;
    static IPEndPoint remoteEp;

    static void Main(string[] args)
    {
        if (args.Length != 3)
        {
            Console.WriteLine("使用方法: {0} <监听端口> <发送端口> <目标IP>", Environment.GetCommandLineArgs()[0]);
            Environment.Exit(1);
        }

        int portno, portno_dest;
        if (!int.TryParse(args[0], out portno))
        {
            Console.WriteLine("监听端口无效");
            Environment.Exit(1);
        }

        string dest_ip = args[2];
        IPAddress dest_addr;
        if (!IPAddress.TryParse(dest_ip, out dest_addr))
        {
            Console.WriteLine("目标IP地址无效");
            Environment.Exit(1);
        }

        if (!int.TryParse(args[1], out portno_dest))
        {
            Console.WriteLine("发送端口无效");
            Environment.Exit(1);
        }

        client = new UdpClient(portno);
        remoteEp = new IPEndPoint(dest_addr, portno_dest);
        Console.WriteLine("Socket已创建");

        Console.CancelKeyPress += delegate {
            client.Close();
            Environment.Exit(0);
        };

        // 启动后台线程处理消息接收
        Thread receiveThread = new Thread(ReceiveMessages);
        receiveThread.IsBackground = true;
        receiveThread.Start();

        // 主线程处理键盘输入与消息发送
        while (true)
        {
            Console.Write("输入消息: ");
            string msg = Console.ReadLine();
            if (string.IsNullOrEmpty(msg)) continue;
            
            byte[] sendBytes = Encoding.ASCII.GetBytes(msg);
            client.Send(sendBytes, sendBytes.Length, remoteEp);
            Console.WriteLine("已发送消息: {0}", msg);
        }
    }

    static void ReceiveMessages()
    {
        try
        {
            while (true)
            {
                byte[] receivedBytes = client.Receive(ref remoteEp);
                string receivedMsg = Encoding.ASCII.GetString(receivedBytes);
                if (!string.IsNullOrEmpty(receivedMsg))
                    Console.WriteLine("\n收到消息: {0}\n输入消息: ", receivedMsg);
            }
        }
        catch (SocketException)
        {
            // 客户端关闭时触发,无需额外处理
        }
    }
}

代码说明

  • 把消息接收逻辑放到后台线程ReceiveMessages中,主线程可以专注处理键盘输入,不再被接收操作阻塞。
  • 收到消息后,通过换行和重新输出输入提示,避免打断用户的输入流程。
  • 设置后台线程IsBackground = true,保证程序退出时该线程会自动终止。

内容的提问来源于stack exchange,提问作者stighy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 02:42:43