【问题标题】:JAVA :I'm not able to send response(json) back to the client from serverJAVA:我无法将响应(json)从服务器发送回客户端
【发布时间】:2021-07-28 11:40:48
【问题描述】:

我有一个将 POST 请求(json)发送到自定义服务器的客户端应用程序。服务器必须向传入的消息发送一个响应(json),但我没有在客户端检测到任何响应。

问题不在客户端,因为如果它向另一台服务器发送请求,那么几秒钟后它会收到响应,我会在日志中看到它。

服务器代码

        try{
            server = new ServerSocket(4321);
            client = server.accept();
            PrintWriter out = new PrintWriter(client.getOutputStream(), true);
            System.out.println("Connection received from " + client.getInetAddress());
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            String s = "SERVER: Started.";

            Gson gson = new Gson();
            String json = gson.toJson(jsonObject.toString());
            while ((s = in.readLine()) != null) {
              System.out.println("RECV: "+s);
              ss = s.split("PUSH\\s");

              out.println("HTTP/1.1 200 OK");
              out.println("application/json;charset=UTF-8");
              out.println("application/json;charset=UTF-8");
              out.println("Jersey/2.27 (HttpUrlConnection 1.8.0_291)");
              out.println("no-cache");
              out.println("no-cache");
              out.println("hostname:4321");
              out.println("keep-alive");
              out.println("392");
              out.println("\n");
              out.println(json);
            } catch(Exception e) {e.printStackTrace();}

我认为我的问题的根源是 out.println()。我不确切知道服务器应该将什么发送回客户端。 响应必须包含 json!

另外,我没有客户端代码。

你能帮忙吗?

【问题讨论】:

  • 服务器收到连接了吗?
  • 是的。我附在下面。 RECV: POST / HTTP/1.1 RECV: Content-Type: application/json;charset=UTF-8 RECV: Accept: application/json; charset=UTF-8 RECV: User-Agent: Jersey/2.27 (HttpUrlConnection 1.8.0_291) RECV: Cache-Control: no-cache RECV: Pragma: no-cache RECV: Host :4321 RECV: Connection: keep-alive RECV: Content-Length: 392

标签: java json client serversocket java-server


【解决方案1】:

虽然我绝对不建议以这种方式编写 HTTP 服务器,但您的代码中至少存在两个问题:

  1. 您缺少标题名称,例如application/json;charset=UTF-8 应改为 Content-Type: application/json;charset=UTF-8
  2. out.println() 使用系统属性 line.separator 定义的行分隔符字符串(例如,\n 用于 Linux)。另一方面,HTTP 需要\r\n,所以最好这样写:out.print("HTTP/1.1 200 OK\r\n");

试试这个:

out.print("HTTP/1.1 200 OK" + "\r\n");
out.print("Content-Type: application/json" + "\r\n");
// you shouldn't need the other headers…
out.print("\r\n");
out.print(json);

【讨论】:

  • 不幸的是,这不起作用。在客户端,我得到了一个 -java.net.SocketTimeoutException: connect timed out.|-。此外,电信没有问题。
  • 尝试在最后关闭使用的资源:@​​987654330@
  • 同样的错误 - java.net.SocketTimeoutException: connect timed out.
  • 我在循环中添加了in.close(); out.close(); client.close();,客户端没有出现错误。
  • 我仍然没有在客户端的日志文件中观察到服务器发送的任何消息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-16
  • 2019-09-16
相关资源
最近更新 更多