2013-10-02 162 views
0

我正在實現一個java多線程服務器。無論客戶端向套接字流寫入什麼內容,都不會在服務器端打印出來。只有在終止客戶端線程後纔會打印數據。問題是什麼? 這裏是我的客戶端代碼發送數據:服務器套接字只在客戶端套接字關閉後打印

BufferWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream() , 
          "UTF-8")); 
writer.write(curr.substring(3)); 
writer.flush(); 

代碼在服務器上:

public class ThreadedEchoServer 
{ 
    public static void main(String[] args) 
    { 
     try 
     { 
     int i = 1; 
     ServerSocket s = new ServerSocket(8189); 

     while (true) 
     { 
      Socket incoming = s.accept(); 
      System.out.println("Spawning " + i); 
      Runnable r = new ThreadedEchoHandler(incoming, i); 
      Thread t = new Thread(r); 
      t.start(); 
      i++; 
     } 
     } 
     catch (IOException e) 
     { 
     e.printStackTrace(); 
     } 
    } 
} 

/** 
    This class handles the client input for one server socket connection. 
*/ 
    class ThreadedEchoHandler implements Runnable 
    { 
     /** 
      Constructs a handler. 
      @param i the incoming socket 
      @param c the counter for the handlers (used in prompts) 
     */ 
     public ThreadedEchoHandler(Socket i, int c) 
     { 
      incoming = i; counter = c; 
     } 

     public void run() 
     { 
      try 
      { 
      try 
      { 
       InputStream inStream = incoming.getInputStream(); 
       OutputStream outStream = incoming.getOutputStream(); 
       System.out.println("Server Running"); 
       Scanner in = new Scanner(inStream);   
       PrintWriter out = new PrintWriter(outStream, true /* autoFlush */); 

       out.println("Hello! Enter BYE to exit."); 

       // echo client input 
       boolean done = false; 
       while (!done && in.hasNextLine()) 
       { 
        String line = in.nextLine(); 
        System.out.println(line); 
        out.println("Echo: " + line);    
        if (line.trim().equals("BYE")) 
         done = true; 
       } 
      } 
      finally 
      { 
       incoming.close(); 
      } 
      } 
      catch (IOException e) 
      { 
      e.printStackTrace(); 
      } 
     } 

回答

0

您正在閱讀行,但你是不是寫行。調用write().後使用BufferedWriter.newline()目前readLine()正在阻止等待換行符或EOS,並且EOS僅在客戶端關閉套接字時發生。

+0

正是我所期待的,非常感謝:) –

相關問題