尝试运行echo服务器时无法读取/写入套接字数据。没有抛出异常,也没有对控制台输入的响应。代码中哪些不正确?
public class Server {
static ServerSocket server;
public static void main(String[] args) throws IOException {
String hostname = "127.0.0.1";
try{
server = new ServerSocket(8888);
} catch (IOException e) {
System.out.println("Could not listen on port 8888");
System.exit(-1);
}
Socket theSocket = null;
try {
theSocket = new Socket(hostname, 8888);
BufferedReader networkIn = new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(theSocket.getOutputStream(), true);
System.out.println("Connected to echo server");
while (true) {
String theLine = userIn.readLine();
if (theLine.equals("."))
break;
out.println(theLine);
out.flush();
System.out.println("networkIn: "+networkIn.readLine());
}
networkIn.close();
out.close();
System.out.println("out.close();");
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:3)
您创建了两个不相关的套接字,一个用于接受连接,另一个用于连接(主机名,8888)。您需要在服务器套接字上调用accept()
以实际连接客户端。请参阅tutorial。
答案 1 :(得分:1)
首先添加Socket client = server.accept();
。然后,您将看到如何重构其余程序。