Java套接字服务器无法回复客户端的原因

Java套接字服务器无法回复客户端的原因,java,sockets,Java,Sockets,我想编写代码,让客户端向服务器发送字符串,服务器打印字符串并回复字符串,然后客户端打印字符串服务器回复。 我的服务器 public class Server { public static void main(String[] args) throws IOException { ServerSocket ss = null; Socket s = null; try { ss = new ServerSocket(34000); s =

我想编写代码,让客户端向服务器发送字符串,服务器打印字符串并回复字符串,然后客户端打印字符串服务器回复。
我的服务器

public class Server {

public static void main(String[] args) throws IOException {
    ServerSocket ss = null;
    Socket s = null;
    try {
        ss = new ServerSocket(34000);
        s = ss.accept();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                s.getInputStream()));
        OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream());

        while (true) {
            String string = in.readLine();
            if (string != null) {
                System.out.println("br: " + string);

                if (string.equals("end")) {
                    out.write("to end");
                    out.flush();
                    out.close();
                    System.out.println("end");
                    // break;
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        s.close();
        ss.close();
    }
}
}
我的客户:

public class Client {
public static void main(String[] args) {
    Socket socket =null;


    try {
        socket = new Socket("localhost", 34000);
        BufferedReader in =new BufferedReader(new InputStreamReader(socket.getInputStream()));
        OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());

        String string = "";
        string = "end";
        out.write(string);
        out.flush();
        while(true){
            String string2 = in.readLine();
            if(string2.equals("to end")){
                System.out.println("yes sir");
                break;
            }
        }


    }  catch (Exception e) {
        e.printStackTrace();
    }finally{
        try {
            System.out.println("closed client");
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
}

有什么不对劲吗?如果我删除客户端类中的代码“while(true)…”,就可以了。

我看不到服务器响应。 你做了一个

System.out.println("br: " + string);
但不是一个

out.write(string);
out.flush();
您应该在写入流的字符串末尾添加
“\r\n”

例如:

客户:

    string = "end";
    out.write(string + "\r\n");
    out.flush();
服务器:

    out.write("to end" + "\r\n");
    out.flush();
    out.close();
    System.out.println("end");
                // break;
将“\n”发送到服务器响应的结尾

outToClient.writeBytes(sb.toString() + "\n"); 

你在读台词,但不是在写台词。添加换行符,或调用
BufferedReader.newline()。

那么您能解释一下发送换行符时发生了什么吗?“公共字符串readLine()读取一行文本。换行符('\n')、回车符('\r')或回车符紧跟换行符中的任何一个都会终止该行。”->当服务器在.readLine()中读取换行符
时,可以在客户端中使用以下命令:
PrintWriter out=new PrintWriter(socket.getOutputStream(),true)
out.println(字符串)您的代码是错误的。如果
readLine()
返回
null
您必须关闭套接字并退出循环。我尝试了,它在ecplise中运行良好。您能告诉我什么是IDE,什么类型的OST在mt情况下不起作用吗: