我用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