Websocket

@Component
@Slf4j
@ServerEndpoint("/websocket") //暴露的ws应用的路径
public class WebSocketServer {
    /**
     * 当前在线客户端数量(线程安全的)
     */
    private static AtomicInteger onlineClientNumber = new AtomicInteger(0);
//    @Autowired
//    private SimulatorMapper simulatorMapper;
    private static ConfigurableApplicationContext applicationContext;
    public static void setApplicationContext(ConfigurableApplicationContext applicationContext) {
        WebSocketServer.applicationContext = applicationContext;
    }

   //当前在线客户端集合(线程安全的):以键值对方式存储,key是连接的编号,value是连接的对象
    private static Map<String, Session> onlineClientMap = new ConcurrentHashMap<>();

    ServerSocket serverSocket = null;
    /**
     * 客户端与服务端连接成功
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        /*
            do something for onOpen
            与当前客户端连接成功时
         */

        onlineClientNumber.incrementAndGet();//在线数+1
        onlineClientMap.put(session.getId(), session);//添加当前连接的session
        log.info("时间[{}]:与用户[{}]的连接成功,当前连接编号[{}],当前连接总数[{}]",
                new Date().toLocaleString(),
                session.getId(),
                onlineClientNumber);
        System.out.println(" 与当前客户端连接成功时");

        try {
            // 创建ServerSocket对象并绑定端口
            InetAddress ipAddress = InetAddress.getByName("127.0.0.1");
            SocketAddress socketAddress = new java.net.InetSocketAddress(ipAddress, 6000);

            // 创建ServerSocket对象并绑定地址和端口
            if (serverSocket == null) {
                serverSocket = new ServerSocket();
                serverSocket.bind(socketAddress);
            }

            Socket clientSocket = serverSocket.accept();
            System.out.println("等待连接...");

            // 创建输入流以接收消息====================最原始的
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            InputStream inputStream = clientSocket.getInputStream();


            while (true) {
                // 处理接收到的消息
                try {
                    byte[] content = InputStreamUtils.readStream(inputStream, 1000 * 60);
                    byte[] jsonByte = new byte[content.length - 8 - 4 ];
                    System.out.println("总长度为:" + jsonByte.length);
                    int index = 0;
                    for (int i = 8; i < content.length - 4; i++) {
                        jsonByte[index] = content[i];
                        index++;
                    }
                    System.out.println("读取长度位:" + index);
                    String jsonstr = new String(jsonByte, StandardCharsets.UTF_8);
                    JSONObject object = JSONObject.parseObject(jsonstr);
                    if(Objects.equals(object.getString("cmdCode"), "4003")){
                    Simulator simulatorData = new Simulator();
                    simulatorData.setCmdCode(object.getString("cmdCode"));
                    simulatorData.setDeviceSn(object.getString("deviceSN"));
                    simulatorData.setTemperature(object.getString("tempData"));
                    simulatorData.setResolution(object.getString("resolution"));
                        simulatorData.setCreateTime( LocalDateTime.now());
                        SimulatorMapper sysUserLoginLogMapper = applicationContext.getBean(SimulatorMapper.class);
                        sysUserLoginLogMapper.insert(simulatorData);
                    }
                    System.out.println("Received JSON: " + object);
                    // 输出解析结果
                    sendAllMessage(object.getString("tempData"));
                } catch (JSONException e) {
                    System.out.println(e);
                    e.printStackTrace();
                }

            }
            /*BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));


            String message;
            while ((message = in.readLine()) != null) {
                // 处理接收到的消息
                try {
                    System.out.println(message);
                    // 输出解析结果
                    sendAllMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }*/
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 客户端与服务端连接关闭
     *
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        /*
            do something for onClose
            与当前客户端连接关闭时
         */
        System.out.println("与当前客户端连接关闭时" + session.getId());
        try {
            // 关闭连接
//            if (clientSocket != null)
//                clientSocket.close();
            if (serverSocket != null)
                serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 客户端与服务端连接异常
     *
     * @param error
     * @param session
     */
    @OnError
    public void onError(Throwable error, Session session) {
    }

    /**
     * 客户端向服务端发送消息
     *
     * @param message
     * @throws IOException
     */
    @OnMessage
    public void onMsg(Session session, String message) throws IOException {
        /*
            do something for onMessage
            收到来自当前客户端的消息时
         */

    }

    // 向所有客户端发送消息(广播)
    private void sendAllMessage(String message) {
        Set<String> sessionIdSet = onlineClientMap.keySet(); // 获得Map的Key的集合
        for (String sessionId : sessionIdSet) { // 迭代Key集合
            Session session = onlineClientMap.get(sessionId); // 根据Key得到value
            session.getAsyncRemote().sendText(message); // 发送消息给客户端
        }
    }


}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值