yinyitong-zhongyuyuan-dll-s.../src/main/java/com/dpkj/modules/keypad/util/WebSocketClient.java

116 lines
3.3 KiB
Java

package com.dpkj.modules.keypad.util;
import com.alibaba.fastjson.JSONObject;
import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
@ClientEndpoint
public class WebSocketClient {
private Session session;
// 密码
private String password = "";
// 是否确认
private boolean confirm = false;
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) {
System.out.println("Connected to WebSocket server");
this.session = session;
}
@OnMessage
public void onMessage(String message) {
System.out.println("Received message: " + message);
// 解析外层 JSON 对象
JSONObject outerObj = JSONObject.parseObject(message);
// 获取 "param" 字段对应的 JSON 对象
JSONObject paramObj = outerObj.getJSONObject("param");
// 从 "param" 对象中获取 "Key" 的值
Integer keyValue = paramObj.getInteger("Key");
if (keyValue != null) {
// 更正
if (keyValue == 8) {
password = password.substring(0, password.length() - 1);
// 取消
} else if (keyValue == 27) {
password = "";
// 确认
} else if (keyValue == 13) {
confirm = true;
} else if (keyValue == 2) {
password += "00";
} else {
password += KEYPAD_MAPPING.get("0x" + Integer.toHexString(keyValue));
}
} else {
System.out.println("未找到 Key 字段或其值为空。");
}
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
System.out.println("Connection closed: " + closeReason.getReasonPhrase());
}
public String getPassword() {
return password;
}
public Boolean getConfirm() {
return confirm;
}
public void close() {
try {
if (session != null && session.isOpen()) {
session.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static final Map<String, String> KEYPAD_MAPPING = new HashMap<>();
static {
// 初始化映射关系
KEYPAD_MAPPING.put("0x30", "0");
KEYPAD_MAPPING.put("0x31", "1");
KEYPAD_MAPPING.put("0x32", "2");
KEYPAD_MAPPING.put("0x33", "3");
KEYPAD_MAPPING.put("0x34", "4");
KEYPAD_MAPPING.put("0x35", "5");
KEYPAD_MAPPING.put("0x36", "6");
KEYPAD_MAPPING.put("0x37", "7");
KEYPAD_MAPPING.put("0x38", "8");
KEYPAD_MAPPING.put("0x39", "9");
KEYPAD_MAPPING.put("0x08", "BACKSPACE"); // 更正按键
KEYPAD_MAPPING.put("0x10", "CLEAR");
KEYPAD_MAPPING.put("0x0D", "ENTER"); // 确认按键
KEYPAD_MAPPING.put("0x1B", "CANCEL"); // 取消
KEYPAD_MAPPING.put("0xA1", "HELP"); // 帮助
KEYPAD_MAPPING.put("0x2E", "DECPOINT");
KEYPAD_MAPPING.put("0x02", "00");
}
}