所以我刚开始学习套接字编程,我决定建立一个非常基本的即时通讯/聊天室。问题是,当我在我的wifi网络上的机器上测试应用程序时它运行正常,但是当我超越时,客户端无法连接。可能是因为我使用的任意端口号?
服务器:
public class MessengerServer {
private static ServerSocket serverSocket;
private static final int PORT=1234;
public static void main(String[] args) throws
IOException {
try{
serverSocket=
new ServerSocket(PORT);
}
catch(IOException e){
System.out.println("Unable to open connection.");
System.exit(1);
}
do{
//wait for client
Socket client= serverSocket.accept();
System.out.println("New Client Accepted");
//create a thread to handle communication
//with this client and pass the constructor
//for this thread the relevant socket
ClientHandler handler= //ClientHandler extends thread
new ClientHandler(client);
handler.start();
}while(true);
}
客户(仅包含相关内容):
public class InstantMessenger extends JFrame implements
ActionListener{
private static final int PORT= 1234;
private static InetAddress host;
private static PrintWriter output;
private static Socket link=null;
private static byte[] ip= new byte[4]; //this is initialised with my IPAddress
//which will not be shown.
InstantMessenger(){
try{
host= InetAddress.getByAddress(ip);
}
catch(UnknownHostException uhEx){
JOptionPane.showMessageDialog
(this,"Unable to find host");
System.exit(0);
}
try{
link =new Socket(host,PORT);
output=
new PrintWriter(link.getOutputStream(),true);
messageArea.append("\nConnected\n");
}
catch(IOException ioEx){
messageArea.append("Unable to connect\n");
}
}
客户端的异常,StackTrace:
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 instantmessenger.InstantMessenger.<init>(InstantMessenger.java:70)
at instantmessenger.InstantMessenger.main(InstantMessenger.java:132)
答案 0 :(得分:0)
可能是由服务器上的连接设置引起的。如果连接设置为公共网络,我认为默认情况下不允许接受来自其他网络的连接。另外,检查是否有任何防火墙设置会阻止来自其他子网的传入连接。