[英]Java TCP Socket
嘗試從套接字讀取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方法阻止了運行上述代碼的客戶端線程。 我如何避免這個問題? 感謝您的幫助。
readLine方法阻止了運行上述代碼的客戶端線程。 我如何避免這個問題?
readLine是一項阻止操作。 如果使用多個線程,則不必擔心。
您正在客戶端上使用readLine()
,它期望以EOL令牌結尾的行,但是您的服務器端代碼未編寫EOL令牌。 使用println()
代替print()
。
為了支持並發客戶端,在服務器上,您需要剝離線程來處理可接受的連接:
while (true) {
// Accept a connection
Socket socket = servSock.accept();
// Spin off a thread to deal with the client connection
new SocketHandler(socket).start();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.