BufferedReader.readline()在socket上聊天时无法正常工作

时间:2015-02-27 17:33:16

标签: java sockets bufferedreader

我使用套接字作为大型应用程序的一部分进行聊天,但是你可以更容易地阅读它,我已经创建了两个显示问题的类。我有一个服务器和一个客户端,服务器打开一个套接字并等待客户端连接后连接它发送一个欢迎消息。在客户端,他们显示欢迎消息,然后输入一个循环写入PrintWriter。在服务器端,它现在将进入一个循环,不断显示来自bufferedReader的文本,但没有打印出来,不确定我是不是很傻但是认为它需要一双新鲜的眼睛,谢谢。

public class Server {

public static boolean running = true;
public static PrintWriter out;
public static BufferedReader in;

public static void main(String[] args) throws IOException {
    ServerSocket s = new ServerSocket(1932);
    while (true) {
        Socket cs = s.accept();
        out = new PrintWriter(cs.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(cs.getInputStream()));
        out.println("Welcome");
        out.flush();
        while (running == true) {
            String input = in.readLine();
            if (input.equals("QUIT")) {
                System.out.println("theyve gone :( ");
                cs.close();
                running = false;
            } else {
                System.out.println(input);
            }

          }

       }
    }
}



public class Client {

public static boolean running = true;
public static PrintWriter out;
public static BufferedReader in;
public static Scanner scan;

public static void main (String [] args) throws IOException{

    Socket so = new Socket("localhost", 1932);
    out = new PrintWriter(so.getOutputStream());
    in = new BufferedReader(new InputStreamReader(so.getInputStream()));
    System.out.println("TYPE QUIT TO LEAVE ");
    System.out.println(in.readLine());
    while(true){
        scan = new Scanner(System.in);
        String message = scan.next();
        out.print(message);
        out.flush();


    }
  }  

}

1 个答案:

答案 0 :(得分:2)

在服务器中,您正在阅读下一行:

String input = in.readLine();

因此服务器会阻塞,直到到达行尾(或流已关闭)。

在客户端,你永远不会发送任何行尾:

out.print(message);