我有一个问题,我确信它很简单,但我不知道答案。
我创建了一个聊天程序,允许两个用户直接相互连接,前提是他们知道另一个用户的端口和 IP。
插座
try {
if (IP != null && checkIP(IP)) {
connection = new Socket(IP, port);
out = new PrintWriter(connection.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
System.out.println("CONNECTED");
printTimestamp();
StyledDocument doc = mainText.getStyledDocument();
Style style = mainText.addStyle("connection", null);
StyleConstants.setForeground(style, Color.ORANGE);
try {
doc.insertString(doc.getLength(), "Connection open to: " + IP + "\n", style);
} catch (Exception e) {
e.printStackTrace();
}
ListenServer.stop();
System.out.println("Making thread");
runnable2 = new InputListener();
thread2 = new Thread(runnable2);
thread2.start();
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + IP);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + IP);
}
服务器套接字
try {
serverSocket = new ServerSocket(ClientWindow.port);
Settings.work = true;
serverSocket.setSoTimeout(3000);
} catch (IOException e) {
System.err.println("Could not listen on port: " + ClientWindow.port);
Settings.work = false;
}
while (running) {
try {
connection1 = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed port: " + ClientWindow.port);
} catch(NullPointerException ne){
JOptionPane.showMessageDialog(ClientWindow.window,
"There was a fatal error in startup.\nPlease close ALL instances of Chattable before attempting to open the program again.",
"Fatal Error",
JOptionPane.ERROR_MESSAGE);
running = false;
}
try {
if (connection1 != null) {
out = new PrintWriter(connection1.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(connection1.getInputStream()));
System.out.println("Accepted over server");
runnable2 = new InputListener();
thread2 = new Thread(runnable2);
thread2.start();
running = false;
StyledDocument doc = mainText.getStyledDocument();
Style style = mainText.addStyle("connection", null);
StyleConstants.setForeground(style, Color.ORANGE);
try {
doc.insertString(doc.getLength(), "[ " + getCurrentTimeStamp() + " ] Connection open to: " + connection1.getRemoteSocketAddress() + "\n", style);
} catch (Exception e) {}
}
} catch (IOException e) {
System.err.println("Couldn't get I/O.");
}
}
该系统在 LAN 上完美运行,但是当您尝试在 Internet 上使用它时,它会从 Socket 代码中引发 IOException。这是使用 TCP 还是 UDP?这对我正在尝试做的事情意味着什么。有没有人有关于如何让它工作的任何提示?是端口不开放的问题吗?
谢谢!