【发布时间】: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?后者用于监听,前者用于连接……