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("\r\n").append("Content-Type: application/json").append("\r\n").append("\r\n").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;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值