你好我正在使用c#进行tcp ip通信,当我的代码从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.Any等可以通过编写代码如何通过tcp ip协议通信机器给我答案谢谢。
答案 0 :(得分:0)
基本上是错误
请求的地址在其上下文中无效
表示计算机上的任何网络接口均未使用 IP地址。简而言之,您可能只需要使用IPAddress.Any
<强>〔实施例强>
server = new TcpListener(IPAddress.Any, port);
进一步阅读
TcpListener Constructor (IPAddress, Int32)
初始化侦听的TcpListener类的新实例 传入连接尝试指定的本地IP地址和 端口号。 备注如果您不关心分配了哪个本地地址,请指定
IPAddress.Any
用于localaddr参数和基础服务 提供商将分配最合适的网络地址
提供指示服务器必须侦听的IP地址 所有网络接口上的客户端活动。