java - 在套接字上聊天时 BufferedReader.readline() 不起作用

标签 java sockets bufferedreader

我使用套接字作为大型应用程序的一部分进行聊天,但是为了让您可以更轻松地阅读它,我创建了 2 个类来显示问题。我有一个服务器和一个客户端,服务器打开一个套接字并等待客户端连接,一旦连接它就会向它们发送一条欢迎消息。在客户端,它们显示欢迎消息,然后进入循环以写入 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();


    }
  }  

}

最佳答案

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

String input = in.readLine();

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

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

out.print(message);

关于java - 在套接字上聊天时 BufferedReader.readline() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28770976/

相关文章:

java - Bufferedreader 验证检查错误

java - 从 lambda 表达式排序和子列表

java - Java 中的重载和多重调度

java - 尝试访问 PoolingHttpClientConnectionManager 时出现 org.testng.TestNGException

python:从 uwsgi 迁移到 http-socket

Java,从带有特殊符号的txt文件中读取数字到二维整数数组中

java - SOLR 1.3 和 SOLR 3.4 之间是否存在主要的架构差异?

postgresql - 如何向世界开放我的 Postgres 数据库

C 使用伯克利套接字发送文件

java - 在Java中将文本文件读入char数组