我在java中实现了一个能够处理多个客户端的echo服务器。即使运行多个客户端,一切都在本地运行。但是当我试图在另一台计算机上运行客户端时,我们得到了
java.net.ConnectException: Connection timed out: connect
在输出中。所以我的问题是,是什么导致了这个?这是我第一次使用服务器,我有点失落。
港口号码是1100。
以下是服务器的类。
ThreadedEchoServer:
import java.net.*;
import java.io.*;
public class ThreadedEchoServer {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java ThreadedEchoServer <port number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
boolean listening = true;
try (ServerSocket serverSocket = new ServerSocket(portNumber)) {
while (listening) {
new EchoThread(serverSocket.accept()).start();
System.out.println("connected");
}
}catch (IOException e) {
System.err.println("Could not listen on port " + portNumber);
System.exit(-1);
}
}
}
EchoThread:
import java.net.*;
import java.io.*;
public class EchoThread extends Thread {
private Socket socket = null;
public EchoThread(Socket socket) {
super("EchoThread");
this.socket = socket;
}
public void run() {
try (
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
) {
String inputLine, outputLine;
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
outputLine = inputLine;
if (outputLine.equals("Bye")) //If neccesassy to break using a command
break;
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
最后,Echo客户端:
import java.io.*;
import java.net.*;
Epublic class EchoClient {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println(
"Usage: java EchoClient <host name> <port number>");
System.exit(1);
}
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
Socket echoSocket = new Socket(hostName, portNumber);
PrintWriter out =
new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn =
new BufferedReader(
new InputStreamReader(System.in))
) {
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
答案 0 :(得分:0)
使用Oracle Java和OpenJDK 1.7.0_55,代码可以正常工作,客户端和服务器运行一个Ubuntu 13.10和Windows 7(切换为客户端运行在一个,服务器运行在另一个上)。
肯定存在网络配置问题(防火墙,NAT)。您可以尝试从远程客户端计算机telnet host port
(即telnet megadeth 1100
)获取另一个打开的端口,以确认您是否正在获得超时。