我正在尝试编写一个(简单的,对于初学者来说)服务器-客户端程序,只是为了建立连接并查看它是否有效。确实如此。只要我留在自己的四堵墙/网络内。一旦我尝试通过我的路由器 IP,客户端就会产生一条非常好的错误消息。所有常见的嫌疑都已排除:路由器端口转发已打开,防火墙不会干扰(好吧,当我关闭它时它仍然不起作用),canyouseeme.org 说它可以与我选择的建立连接服务器运行时的端口。
这是服务器的源代码,因为我发现可以通过命令行进行一些远程登录。
当我尝试建立连接时,它只是说 Could not open connection to the host, on port 49163:Connection failed
服务器:
import java.net.*;
import java.io.*;
public class ChatServer {
public static void main(String[] args) throws IOException {
ServerSocket server = null;
try {
System.setProperty("java.net.preferIPv4Stack" , "true");
server = new ServerSocket(49163);
} catch (IOException e) {
System.err.println("Could not listen on port: 49163.");
System.exit(1);
}
Socket client = null;
try {
client = server.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
BufferedReader in = new BufferedReader(newInputStreamReader(client.getInputStream()));
String inputLine;
String outputLine;
out.println("Connection established");
while ((inputLine = in.readLine()) != null) {
if (inputLine.equals("exit")) {
break;
}
outputLine = inputLine;
out.println(outputLine);
}
out.close();
in.close();
client.close();
server.close();
System.out.println("Server offline");
}
}
哦,是的,preferIP4vStack 是我在 Stackoverflow 上学到的东西,但它似乎对我不起作用。
出于某种原因,我无法包含客户端的代码,我不断收到有关格式设置的消息,但我就是想不通。但我的看法是,我什至无法通过命令行连接(当我尝试连接到“真实”IP 时),因此客户端不必参与。但是对于无论如何都想看到错误的人来说:
java.net.ConnectException: Connection refused: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(Unknown Source) at java.net.PlainSocketImpl.connectToAddress(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.<init>(Unknown Source) at java.net.Socket.<init>(Unknown Source) at ChatClient.main(ChatClient.java:12)
最佳答案
Could not open connection to the host, on port 49163:Connection failed
不,它没有。那不是 Java 消息。你的代码说,当你捕获到一个 ConnectException 时,它有自己的更详细的消息。打印出来,您可能有希望找到问题所在。编写您自己的消息并抑制异常告诉您的内容很少是一个好主意。
消息可能是以下之一:
- 'connection refused',表示你弄错了目标主机或端口,或者有防火墙
- 'connection timed out',这是网络连接问题
- 'no route to host',这是IP路由问题
- 'unknown host',这再次意味着您弄错了服务器名称。
关于Java网络服务器-客户端错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14715972/