【问题标题】:Able to get a connection with TCPClient but not TCPListener [duplicate]能够与 TCPClient 但不能与 TCPListener 建立连接 [重复]
【发布时间】:2018-01-10 22:23:05
【问题描述】:

我目前正在尝试从端口读取消息,出于某种原因,我可以使用 TCPClient 执行此操作,但是在尝试使用 TCPListener 时收到错误消息。我想知道是否有人可以告诉我为什么,或者我可能哪里出错了?

这是有效的代码,我可以从以下位置读取消息:

 public static NetworkStream nwStream;
 public static TcpClient client = new TcpClient();
 public const string address = "10.10.10.151";
 public const int port = 9004; //both never change


 public MainWindow()
    {
        InitializeComponent();

        client.Connect(address, port);

        connected = true;

        if (connected == true)
        {
            readInTxtBox.Text = "Connected";
        }
}

这是引发错误的代码:

 static void Main(string[] args)
    {
        IPAddress ipAddress = IPAddress.Parse("10.10.10.151");
        TcpListener Listener = new TcpListener(ipAddress, 9004);
        Listener.Start(); //this is where the error is!
        Socket Client = Listener.AcceptSocket();
        using (NetworkStream PMS_NS = new NetworkStream(Client))
        {
            StreamReader sr = new StreamReader(PMS_NS);
            Console.WriteLine(sr.ReadLine());
        }
        Console.ReadLine();
    }

错误提示:

System.dll 中出现“System.Net.Sockets.SocketException”类型的未处理异常 附加信息:请求的地址在其上下文中无效

【问题讨论】:

  • 是什么让您认为可以将 TcpClient 换成 TcpListener?后者用于监听,前者用于连接……

标签: c# sockets


【解决方案1】:

您只能绑定到您正在运行的机器的本地 IP - 大概10.10.10.151 不是其中之一。您可以使用IPAddress.Any 绑定到任何可用的接口,这通常是服务器所需的行为。或者,使用 TCPListener.Create 静态函数只指定端口并跳过指定 IP。

如果您确实想绑定到特定的本地 IP,那么您当前的方法应该没问题,只需使用分配给您的网络接口之一的 IP(请参阅 Windows 上的 ifconfig 或 Linux 上的 ip a),而不是10.10.10.151.

【讨论】:

    【解决方案2】:

    也许给定的 IP 地址不是您的 IP 地址。尝试使用

     TcpListener Listener = new TcpListener(IPAdress.Any, 9004);
    

    而不是

    IPAddress ipAddress = IPAddress.Parse("10.10.10.151");
    TcpListener Listener = new TcpListener(ipAddress, 9004);
    

    【讨论】:

      猜你喜欢
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-16
      • 2018-04-24
      • 1970-01-01
      • 2019-05-10
      相关资源
      最近更新 更多