Java 在套接字上聊天时BufferedReader.readline()不工作
我使用套接字作为大型应用程序的一部分进行聊天,但是为了便于阅读,我创建了两个类来说明这个问题。我有一个服务器和一个客户机,服务器打开一个套接字,等待客户机连接,一旦连接,它会向他们发送欢迎消息。在客户端,它们显示欢迎消息,然后输入一个循环以写入PrintWriter。在服务器端,它现在将进入一个循环,不断显示来自bufferedReader的文本,但是没有打印出来,不确定我是否愚蠢,但认为它需要一双新眼睛,谢谢Java 在套接字上聊天时BufferedReader.readline()不工作,java,sockets,bufferedreader,Java,Sockets,Bufferedreader,我使用套接字作为大型应用程序的一部分进行聊天,但是为了便于阅读,我创建了两个类来说明这个问题。我有一个服务器和一个客户机,服务器打开一个套接字,等待客户机连接,一旦连接,它会向他们发送欢迎消息。在客户端,它们显示欢迎消息,然后输入一个循环以写入PrintWriter。在服务器端,它现在将进入一个循环,不断显示来自bufferedReader的文本,但是没有打印出来,不确定我是否愚蠢,但认为它需要一双新眼睛,谢谢 public class Server { public static boole
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);
readLine()一直读取,直到您编写换行符为止。如果你不写一个,它会一直读,直到你关闭连接或者内存耗尽。