【发布时间】: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