ソケットから 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 メソッドは、上記のコードを実行しているクライアント スレッドをブロックしています。どうすればその問題を回避できますか? 助けてくれてありがとう。