2012-08-29 188 views
0

我在嘗試從套接字讀取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的方法阻止運行上述代碼的客戶端線程。我怎樣才能避免這個問題?感謝您的幫助。

+0

考慮使用多線程服務器/客戶端。請參閱[這裏]和[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) –

+0

你正在閱讀的線路,但你不寫行。 – EJP

回答

0

您在客戶端上使用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(); 
} 
0

readLine方法阻止運行上述代碼的客戶端線程。我怎樣才能避免這個問題?

readLine是一個阻塞操作。如果你使用多個線程,這不一定是個問題。