服务器套接字仅在客户端套接字关闭后打印

时间:2013-10-02 05:53:23

标签: sockets serversocket

我正在实现一个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();
          }
       }

1 个答案:

答案 0 :(得分:0)

你正在读行,但你不是在写行。调用BufferedWriter.newline()后使用write().目前readLine()阻止等待换行符或EOS,而EOS仅在客户端关闭套接字时发生。