1
嘗試運行echo服務器時,無法讀取/寫入數據到套接字。沒有異常拋出,並且沒有響應控制檯輸入。代碼中有什麼不正確?無法從套接字的InputStream獲取數據
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();
}
}
}