2017-02-14 113 views
1

我想循环扫描仪读取一行,通过一个printStream立即发送到客户谁应该打印它,然后等待从服务器的另一行。爪哇PrintStream立即outputStream与扫描仪和循环

我的客户端在打印第一条消息后一直卡住,之后只返回null。我想我不应该在Server.java中调用printStream.close(),但是直到关闭它才会传输消息。 printSteam.flush似乎没有做任何事情。

相关的代码:

Server.java

 ServerSocket serverSocket = new ServerSocket(1234); 
     Socket connectionSocket = serverSocket.accept(); 
     OutputStream outputStream = connectionSocket.getOutputStream(); 

     Scanner sc = new Scanner(System.in); 

     while(true) { 

      System.out.print("Pass me a message: "); 
      String input = sc.nextLine(); 

      final PrintStream printStream = new PrintStream(outputStream); 
      printStream.print(input); 
      printStream.flush(); 
      printStream.close(); 
     } 

Client.java

 Socket connectionSocket = new Socket("localhost", 1234); 
     InputStream inputStream = connectionSocket.getInputStream(); 

     String result = ""; 
     BufferedReader inFromServer = new BufferedReader(new InputStreamReader(inputStream)); 

     while (true) { 

      result = inFromServer.readLine(); 
      System.out.println("Message: "+result); 
     } 

谢谢您的帮助!

+0

什么是'outputStream'? – shmosel

+0

它是一个正常的OutputSteam。我更新了片段。 – JoJota

回答

1

一旦你关闭PrintStream就完成了。如果它后面有一个套接字连接,它将关闭该连接。相反,在循环之外创建PrintStream并且不要关闭它

final PrintStream printStream = new PrintStream(outputStream); 
    while(true) { 

     System.out.print("Pass me a message: "); 
     String input = sc.nextLine(); 

     printStream.print(input); 
     printStream.flush(); 
    } 
+0

谢谢,但我的客户现在不会打印任何消息。 – JoJota

+0

没关系,我在消息后添加了\ n的工作! – JoJota

+0

@JoJota太好了!当你有一刻时,请点击绿色的复选标记,表示这已经解决了你的问题 – ControlAltDel