package com.dpkj.modules.keypad.util; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import javax.websocket.*; import java.io.IOException; import java.net.URI; @ClientEndpoint @Slf4j public class WebSocketClient { private Session session; private String password = ""; public WebSocketClient(String uri) { try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); session = container.connectToServer(this, new URI(uri)); } catch (Exception e) { e.printStackTrace(); } } @OnOpen public void onOpen(Session session) { this.session = session; } @OnMessage public void onMessage(String message) { // 解析外层 JSON 对象 JSONObject outerObj = JSONObject.parseObject(message); // 获取 "param" 字段对应的 JSON 对象 JSONObject paramObj = outerObj.getJSONObject("param"); // 从 "param" 对象中获取 "Key" 的值 Integer keyValue = paramObj.getInteger("Key"); if (keyValue != null) { Integer i = parseAsciiToDigit(keyValue); if (i != -1) { password += i.toString(); } } else { log.info("按键事件返回值,未找到 Key 字段或其值为空。"); } } @OnClose public void onClose(Session session, CloseReason closeReason) { } public String getPassword() { return password; } public void close() { try { if (session != null && session.isOpen()) { session.close(); } } catch (IOException e) { e.printStackTrace(); } } public static Integer parseAsciiToDigit(Integer asciiValue) { // 检查输入的 ASCII 值是否在 '0' 到 '9' 的范围内 if (asciiValue >= 48 && asciiValue <= 57) { // 将 ASCII 值转换为对应的数字 return asciiValue - 48; } else { // 如果输入的 ASCII 值不在 '0' 到 '9' 的范围内,返回 -1 表示无效输入 return -1; } } }