【问题标题】:Client - Server on same machine using UDP客户端 - 同一台机器上使用 UDP 的服务器
【发布时间】:2013-11-26 03:12:25
【问题描述】:

我正在尝试在我的机器上用 c# 模拟客户端 - 服务器场景。但是当我执行它时会弹出一个异常说:

没有这样的主机是已知的

我的代码:

namespace TCPClient
{
    public class Program
    {
        public static void Main(string[] args)
        {
            UdpClient udpc = new UdpClient(args[0], 2055);
            IPEndPoint ep = null;
            while (true)
            {
                Console.Write("Name: ");
                string name = Console.ReadLine();
                if (name == "") break;
                byte[] sdata = Encoding.ASCII.GetBytes(name);
                udpc.Send(sdata, sdata.Length);
                byte[] rdata = udpc.Receive(ref ep);
                string job = Encoding.ASCII.GetString(rdata);
                Console.WriteLine(job);
            }
        }
    }
}

我不明白我哪里出错了。

【问题讨论】:

    标签: c# udp


    【解决方案1】:

    感谢开发者!您的回答很有帮助,但我找到了最简单的方法。

     public class Program
     {
        public static void Main(string[] args)
        {
            UdpClient udpc = new UdpClient( System.Net.Dns.GetHostName(), 2055);
            IPEndPoint ep = null;
            while (true)
            {
                Console.Write("Name: ");
                string name = Console.ReadLine();
                if (name == "") break;
                byte[] sdata = Encoding.ASCII.GetBytes(name);
                udpc.Send(sdata, sdata.Length);
                byte[] rdata = udpc.Receive(ref ep);
                string job = Encoding.ASCII.GetString(rdata);
                Console.WriteLine(job);
            }
        }
     }
    

    【讨论】:

      【解决方案2】:

      我相信你的问题在于这个电话:

      byte[] rdata = udpc.Receive(ref ep)
      

      问题在于,为了能够监听任何传入的内容,您首先需要将 UdpClient 绑定到一个有效的端点 - 像这样:

      IPEndPoint ep = new IPEndPoint(IPAddress.Any, 8192);
      //You will be listening to port 8192.
      

      另外,请记住,您不能同时从同一个 UdpClient 监听和发射;您将需要两个客户端,如果您想为两者使用相同的 IP 端口,则需要使用 SocketOptionName.ReuseAddress 参数初始化该类。以下帖子提供了一个很好的例子:

      Connecting two UDP clients to one port (Send and Receive)

      【讨论】:

        【解决方案3】:

        隔离问题。您正在调用 new UdpClient(args[0], 2055)udpc.Receive(ref ep) 可以引发此异常,但不要说哪个会。要么调试它,要么用一个常量字符串试试:

        string host = args[0];
        new UdpClient(host, 2055);
        

        然后您会看到host 很可能不是现有的主机名。如果是,请检查您对ep 的操作:什么都没有,所以它将是null。我猜你会想要监听任何 UDP 数据报 as explained in the documentation,所以指定端点:

        ep = new IPEndPoint(IPAddress.Any, 0);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-18
          • 1970-01-01
          • 2017-06-01
          • 1970-01-01
          • 2013-08-19
          • 1970-01-01
          • 2011-11-20
          • 1970-01-01
          相关资源
          最近更新 更多