gpt4 book ai didi

c# - 服务器给出异常并且无法启动

转载 作者:可可西里 更新时间:2023-11-01 02:53:12 24 4
gpt4 key购买 nike

最近我开始学习 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);

最佳答案

错误消息 The requested address is not valid in its context 表示您使用的 IP 地址未绑定(bind)到计算机上的任何网络接口(interface)。您通常不希望对您收听的特定 IP 地址进行硬编码(例如,如果您的机器通过 DHCP 获取 IP 地址,它可能会更改)。

更好的方法是使用 IPAddress.Any监听机器上可用的所有 IP 地址(即网络接口(interface))。

关于c# - 服务器给出异常并且无法启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53988833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com