服务器给出异常并且无法启动
Posted
技术标签:
【中文标题】服务器给出异常并且无法启动【英文标题】:Server gives exception and fails to start 【发布时间】:2018-12-31 15:05:02 【问题描述】:最近我开始学习 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);
【问题讨论】:
哪一行抛出异常? 服务器应该启动时的第 26 行。 Here 是 MSDN 参考,用于将TcpListener
用作参考。 - 首先,我希望这不是您在问题中给出的实际IP
,如果是,我建议(在问题内)更改它以确保安全。然后,我会验证port 8080
上是否已经有任何东西在运行。你试过不同的端口吗?
我试图更改端口,但它说 ip 由于某种原因它无效,但是当我从具有相同端口的本地 ipv4 地址启动它时它可以工作。
它只适用于本地 ip。
【参考方案1】:
错误消息The requested address is not valid in its context
表示您使用的IP 地址未绑定到您机器上的任何网络接口。
您通常不希望硬编码您收听的特定 IP 地址(例如,如果您的机器通过 DHCP 获取 IP,它可能会更改)。
更好的方法是使用IPAddress.Any 监听机器上所有可用的 IP 地址(即网络接口)。
【讨论】:
以上是关于服务器给出异常并且无法启动的主要内容,如果未能解决你的问题,请参考以下文章
无法启动tomcat并且tomcat的catalina.out日志文件报错“ContainerBase.addChildInternal ContainerBase.addChild: start“