我是靠谱客的博主 快乐红牛,最近开发中收集的这篇文章主要介绍Java自定义Socket服务器响应JSON数据,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

  1. 引入 com.alibaba.fastjson.JSON 依赖
  2. 自定义服务器
  3. 响应JSON数据

需要引入 com.alibaba.fastjson.JSON的依赖

import com.alibaba.fastjson.JSON;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class Server {
public void init(String host, int port) {
try {
ServerSocket serverSocket = new ServerSocket();
System.out.println("服务器 " + host + ":" + port + " 启动成功...");
SocketAddress socketAddress = new InetSocketAddress(host, port);
serverSocket.bind(socketAddress);
AtomicInteger integer = new AtomicInteger(0);
while (true) {
Socket client = serverSocket.accept();
System.out.println();
int i = integer.incrementAndGet();
System.out.println(i + ":" + client.toString());
new HandlerThread(client, i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private class HandlerThread implements Runnable {
private Socket socket;
private int index;
public HandlerThread(Socket socket, int index) {
this.socket = socket;
this.index = index;
new Thread(this).start();
}
@Override
public void run() {
try {
DataInputStream input = new DataInputStream(socket.getInputStream());
/**
* 假设服务器就收的数据格式为Map的JSON串,如下所示:
* {"msgId":"ea7f2cd7-34f1-4f4e-886e-ef395e29cf7c","list":[{"data":12},{"data":1518}]}
*/
Map<String, Object> readData = readData(input);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
String msgId = String.valueOf(readData.get("msgId"));
String json = writeData(msgId);
StringBuilder sb = new StringBuilder();
sb.append("HTTP/1.1 200 ok").append("rn").append("Content-Type: application/json").append("rn").append("rn").append(json);
TimeUnit.MILLISECONDS.sleep(100);
out.write(sb.toString().getBytes());
out.close();
input.close();
} catch (Exception e) {
System.out.println(this.index + ":" + this.socket.toString() + ":" + e.getMessage());
} finally {
if (socket != null) {
try {
socket.close();
} catch (Exception e) {
socket = null;
System.out.println("服务端 finally 异常:" + e.getMessage());
}
}
}
}
public Map<String, Object> readData(DataInputStream input) throws Exception {
byte[] bytes = new byte[input.available()];
input.read(bytes);
String data = new String(bytes);
String[] split = data.split(System.getProperty("line.separator"));
Map<String, Object> map = JSON.parseObject(split[split.length - 1], Map.class);
System.out.println(map.get("list"));
return map;
}
public String writeData(String msgId) throws Exception {
Map<String, Object> result = new HashMap<>();
result.put("code", 0);
result.put("data", msgId);
String resultData = JSON.toJSONString(result);
return resultData;
}
}
}

最后

以上就是快乐红牛为你收集整理的Java自定义Socket服务器响应JSON数据的全部内容,希望文章能够帮你解决Java自定义Socket服务器响应JSON数据所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(57)

评论列表共有 0 条评论

立即
投稿
返回
顶部