java - 为什么服务器向客户端发送空白字符串?

标签 java sockets

我正在使用套接字和线程用java编写程序。在我的客户端类中,我有一个方法,客户端可以添加服务并将它们发送到服务器。服务器接收数据并将其存储到ArrayList中。我的问题是,存储服务后我想将消息发送回客户端,这样他就会知道服务已成功添加,但不幸的是我收到的是一个空白字符串。

这是我的代码:

  //method from client class

  private static void addServices() throws IOException{
   input= new BufferedReader(new InputStreamReader(System.in));
   inputClient=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
   output= new PrintWriter(clientSocket.getOutputStream());
   System.out.print("\nName of service: ");
   String name=input.readLine();
   output.println(name);
   output.flush();
   System.out.print("\nData of service: ");
   String data=input.readLine();
   output.println(data);
   output.flush();
   String getMsg;
   getMsg=inputClient.readLine(); //here I got blank string from server
   System.out.println(getMsg);
}


  //method from Server class

  private void addServices()throws IOException{
    reader= new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    output=new PrintWriter(clientSocket.getOutputStream());
    String name=reader.readLine();
    String data=reader.readLine();
    serviceList.add(new Service(login,name,true,data));
    String msg="\nService added succesfully.";
    output.println(msg); // here's message I wanna sent to the client
    output.flush();
  }

你能解释一下我做错了什么以及为什么吗?感谢您的帮助。

最佳答案

事情是这样的: 消息“\n服务添加成功。” 已发送至客户端。然后,inputClient.readLine() 方法读取第 0 个字符和行终止字符之间的字符串,该字符是消息中 "\n" 之前的空字符串。尝试删除 \n,它应该可以正确获取消息。

关于java - 为什么服务器向客户端发送空白字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47249902/

相关文章:

java - 如何使用jexcel读取excel?

java - 将数字字(字符串)转换为其整数值

java - 无法加载 com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask。 java.lang.IllegalStateException

java - JTextPane 文本可能由于范围问题而未更新

java - 在 JAVA 中列出远程计算机上目录内特定类型的所有文件

java - 使用java套接字传输文件时获取文件名和长度

java - 当输出到控制台 PrintWriter 时文本向右移动

c - 如何在C中获取套接字的地址ip

python - 通过 python 套接字发送文本 "http"

java - Hibernate 在绑定(bind)到 Java 时间戳对象时忽略数据库时区信息