尝试从套接字读取 InputStream 时遇到阻塞问题。
这是服务器端的代码:
public static void main(String[] args) throws Exception {
if (args.length != 1) {
throw new IllegalArgumentException("Parameter : <Port>");
}
int port = Integer.parseInt(args[0]); // Receiving port
ServerSocket servSock = new ServerSocket(port);
String s;
Socket clntSock = servSock.accept();
System.out.println("Handling client at "
+ clntSock.getRemoteSocketAddress());
in = new BufferedReader(
new InputStreamReader(clntSock.getInputStream()));
out = new PrintWriter(clntSock.getOutputStream(), true);
while (true) {
s = in.readLine();
System.out.println("s : " + s);
if (s != null && s.length() > 0) {
out.print(s);
out.flush();
}
}
}
这是我发送和接收数据(字符串)的客户端部分:
while (true) {
try {
// Send data
if (chatText.getToSend().length() != 0) {
System.out.println("to send :"
+ chatText.getToSend().toString());
out.print(chatText.getToSend());
out.flush();
chatText.getToSend().setLength(0);
}
// Receive data
if (in.ready()) {
System.out.println("ready");
s = in.readLine();
System.out.println("s : " + s);
if ((s != null) && (s.length() != 0)) {
chatText.appendToChatBox("INCOMIN: " + s + "\n");
}
}
} catch (IOException e) {
cleanUp();
}
}
readLine 方法正在阻塞运行上述代码的客户端线程。我怎样才能避免这个问题?感谢您的帮助。