客户端中的NoRouteToHostException [英] NoRouteToHostException in Client
问题描述
我正在开发涉及服务器和客户端的程序,我正在尝试侦听端口,然后从客户端向该端口发送消息。但是,这样做我得到 NoRouteToHostException
。我做了一个简单的客户端和服务器应用程序来测试我是否可以发送和接收给定服务器和客户端的消息。
I am working on a program that involves a server and a client and I am try to listen on a port and then send messages to that port from a client. However, on doing so I get NoRouteToHostException
. I made a simple Client and Server application to test if I can send and receive messages for my given server and client.
服务器:
public class Server{
public static void main(String [] args) throws Exception{
ServerSocket s = new ServerSocket(8001);
s.accept();
}
}
客户:
public class Client{
public static void main(String [] args){
Socket s = new Socket(IP, port);
PrintWriter p = new PrintWriter(s.getOutputStream(), true);
p.println("Hello World");
s.close();
}
}
Exception in thread "main" java.net.NoRouteToHostException: No route to host
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
我试图ping服务器,它也经历了。此外,如果我在localhost上运行客户端,我不会得到异常。当客户端在不同的系统上运行时,我才会收到异常。
I tried to ping the server and it went through as well. Also, if I run the client on the localhost I don't get an exception. I only get the exception when the client is running on a different system.
编辑
在8080上运行服务器时,它作品。我尝试通过 iptables --policy INPUT ACCEPT
允许所有传入的连接到服务器,但这仍然不允许我在端口8001上侦听
EDIT
When running the server on 8080, it works. I tried allowing all incoming connections to the server by doing iptables --policy INPUT ACCEPT
, but that still doesn't allow me to listen on port 8001
推荐答案
这种情况只有在端口由于其间的防火墙而无法访问时才会发生。这个防火墙甚至可以在客户端或服务器机器上的任何地方。
ping
是检查主机是否可访问但不在端口上8001.从 ping
,确认主机可访问。
This could only happen, when the port is not accessible because of a firewall in between. This firewall could be anywhere even on the client or the server machine.
ping
is to check if the host is accessible which it is but not on port 8001. From ping
, it is confirmed that the host is accessible.
尝试在另一个常开端口(如80,443,8080等)上运行服务器程序。网络/防火墙管理员通常允许这些端口打开并可访问。请注意,对于端口80,443(任何小于1024的端口)将需要root访问权限绑定到它(在服务器上)。
Try running the server program on another generally open port such as 80, 443, 8080 etc. The network / firewall administrators generally allow these ports to be open and accessible. Note that for port 80, 443 (any port less than 1024) would require root access to bind to it (on the server that is).
这篇关于客户端中的NoRouteToHostException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!