【发布时间】:2018-05-22 16:07:39
【问题描述】:
你好,当我的代码从 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 协议与机器通信谢谢。
【问题讨论】:
标签: c# tcp tcpclient tcp-ip tcplistener