最近,我开始学习c#中的Tcp / ip套接字,因此我观看了教程并在线阅读了有关内容。我按照教程进行操作,制作了客户端服务器应用程序,该应用程序将简单文本发送到同一网络上的服务器。我试图“升级”并使客户端与通过服务器在不同网络上的其他客户端通信。但是现在服务器无法开始说“请求的地址在其上下文中无效”。
First was server running as localhost, but now when I want to clients that are in different networks communicate through server , server needs to run on my ip address so other client in different network could connect. I did IPAddress ip = IPAddress.Parse("my IP"); and TcpListener server = new TcpListener(ip, 10000); I tried using different ports but its still the same.
This is what exceptions tells me
at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Bind(EndPoint localEP)
at System.Net.Sockets.TcpListener.Start(Int32 backlog)
at System.Net.Sockets.TcpListener.Start()
IPAddress ip = IPAddress.Parse("192.168.1.5"); //Mock IP
TcpListener server = new TcpListener(ip, 8080);
TcpClient client = default(TcpClient);
TcpClient client2 = default(TcpClient);
try
{
server.Start();
Console.WriteLine("Server started...");
}
catch(Exception ex)
{
Console.WriteLine("Server failed to start... {0}",ex.ToString());
Console.Read();
}
while (true)
{
client = server.AcceptTcpClient();
client2 = server.AcceptTcpClient();
byte[] receivedBuffer = new byte[1000];
byte[] receivedBuffer2 = new byte[1000];
NetworkStream stream = client.GetStream();
NetworkStream stream2 = client2.GetStream();
stream.Read(receivedBuffer, 0, receivedBuffer.Length);
stream2.Read(receivedBuffer2, 0, receivedBuffer2.Length);
StringBuilder message = new StringBuilder();
foreach (byte b in receivedBuffer)
{
if (b.Equals(126))
{
break;
}
else
{
message.Append(Convert.ToChar(b).ToString());
}
}
StringBuilder message2 = new StringBuilder();
foreach (byte g in receivedBuffer2)
{
if (g.Equals(126))
{
break;
}
else
{
message2.Append(g);
}
}
//string message = Encoding.ASCII.GetString(receivedBuffer, 0, receivedBuffer.Length);
Console.WriteLine(message.ToString() + message.Length);
Console.WriteLine(message2.ToString() +message2.Length);
答案 0 :(得分:0)
错误消息The requested address is not valid in its context
表示您使用的IP地址未绑定到计算机上的任何网络接口。
通常,您不想对您监听的特定IP地址进行硬编码(例如,如果您的计算机通过DHCP获得的IP地址可能会更改)。
更好的方法是使用IPAddress.Any来监听机器上可用的所有IP地址(即网络接口)。