我用Java创建了一个简单的echo服务器。当我在本地尝试时,它应该可以正常工作。但是,当我尝试使用服务器运行的IP地址和端口号从另一台计算机连接它时,它永远不会连接。从另一台计算机连接到服务器还有其他事情吗?如何连接到运行Java服务器的其他计算机?
import java.net.Socket;
import java.net.ServerSocket;
public class EchoServer {
public static void main(String[] args) throws Exception {
// create socket
int port = 4444;
ServerSocket serverSocket = new ServerSocket(port);
System.err.println("Started server on port " + port);
// repeatedly wait for connections, and process
while (true) {
// a "blocking" call which waits until a connection is requested
Socket clientSocket = serverSocket.accept();
System.err.println("Accepted connection from client");
// open up IO streams
In in = new In (clientSocket);
Out out = new Out(clientSocket);
// waits for data and reads it in until connection dies
// readLine() blocks until the server receives a new line from client
String s;
while ((s = in.readLine()) != null) {
out.println(s);
}
// close IO streams, then socket
System.err.println("Closing connection with client");
out.close();
in.close();
clientSocket.close();
}
}
}
也许防火墙阻止了你的连接。尝试禁用它进行简短的测试。你是否通过路由器与另一台计算机分开? – Tudor 2012-03-26 20:48:49
添加代码如何创建服务器套接字? – 2012-03-26 20:49:16
调用'netstat -na'并检查您绑定服务器的地址。它应该是0.0.0.0:*(或者::: *对于ipv6) – 2012-03-26 20:51:39