我在嘗試從套接字讀取InputStream時遇到阻塞問題。
這裏是服務器端的代碼:
Java TCP套接字
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的方法阻止運行上述代碼的客戶端線程。我怎樣才能避免這個問題?感謝您的幫助。
考慮使用多線程服務器/客戶端。請參閱[這裏]和[this](http://www.kieser.net/linux/java_server.html)以及[http://tutorials.jenkov.com/java-multithreaded-servers/multithreaded-server.html]這裏也是](http://www.ase.md/~aursu/ClientServerThreads.html) –
你正在閱讀的線路,但你不寫行。 – EJP