侦听来自其他计算机的数据时,请求的地址在其上下文中无效



您好,当我的代码侦听IP时,我正在使用C#进行TCP IP通信,然后它给我错误消息,请求的地址在其上下文中无效。 这是代码。

TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 5555;
IPAddress localAddr = IPAddress.Parse("10.3.0.234");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
Console.WriteLine("Sent Data:" + msg);
// Send back a response.
//  stream.Write(msg, 0, msg.Length);
//   Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}

实际上,此IP是在机器发送结果的机器中配置的。 实际上我已经看到了许多相同问题的答案,但我不知道在哪里更改 IPAddress.任何等都可以通过编写代码给我答案如何通过 TCP IP 协议与机器通信谢谢。

基本上,错误

请求的地址在其上下文中无效

表示给定的IP 地址未被计算机上的任何网络接口使用。简而言之,您可能只需要使用 IPAddress.Any

示例

server = new TcpListener(IPAddress.Any, port);

延伸阅读

TcpListener Constructor (IPAddress, Int32(

初始化侦听 对指定本地 IP 地址的传入连接尝试,以及 端口号。言论如果您不关心分配哪个本地地址,请指定 本地地址参数和基础服务的IPAddress.Any提供程序将分配最合适的网络地址

IPAddress.any

提供指示服务器必须侦听的 IP 地址 所有网络接口上的客户端活动。

最新更新