我已经有这个问题一段时间了,虽然我的努力和我的朋友帮助我似乎无法克服这个问题。
我的问题是我正在尝试使用套接字在客户端和服务器之间建立连接,这实际上很常见,但由于某种原因,客户端似乎无法连接到服务器,不知道为什么,这是我解决问题的尝试
1- 我使用http://portforward.com/打开我的路由器上使用的“zhone”类型的端口 2- 我多次更改端口,每次我使用 PFPortChecker 来查看我的端口是否打开
我的代码相当简单,它打开服务器,当客户端连接到它时,服务器发送日期和时间
我的服务器代码看起来像这样
public class DateServer {
/** Runs the server. */
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket(6780);
try {
while (true) {
Socket socket = listener.accept();
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(new Date().toString());
} finally {
socket.close();
}
}
} finally {
listener.close();
}
}
}
我的客户代码看起来像这样
public class DateClient {
/** Runs the client as an application. First it displays a dialog box asking for the IP address or hostname of a host running the date server, then connects to it and displays the date that it serves. */
public static void main(String[] args) throws IOException {
//I used my serverAddress is my external ip address
Socket s = new Socket(serverAddress, 6780);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
System.exit(0);
}
}
即使我继续尝试
3-我关闭了防火墙以防万一
4-我在我的服务器套接字中添加了连接超时
经过我所有的尝试,我总是得到这个错误
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(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 DateClient.main(DateClient.java:13)
注意 DateClient.java:13 是这一行 Socket s = new Socket(serverAddress, 6780);
请帮我解决这个问题,在此先感谢