60 lines
2.0 KiB
Java
60 lines
2.0 KiB
Java
package org.example;
|
|
|
|
import javax.websocket.OnClose;
|
|
import javax.websocket.OnMessage;
|
|
import javax.websocket.OnOpen;
|
|
import javax.websocket.Session;
|
|
import javax.websocket.server.ServerEndpoint;
|
|
import java.io.IOException;
|
|
import java.util.Set;
|
|
import java.util.concurrent.CopyOnWriteArraySet;
|
|
|
|
@ServerEndpoint("/ws")
|
|
public class WsServer {
|
|
private static final Set<Session> sessions = new CopyOnWriteArraySet<>();
|
|
|
|
@OnOpen
|
|
public void onOpen(Session session) {
|
|
sessions.add(session);
|
|
System.out.println("WebSocket连接已建立: " + session.getId());
|
|
// 推送所有扫码枪列表给前端(使用修改后的方法名)
|
|
// String deviceListJson = Main.getAllDevicesJson();
|
|
// try {
|
|
// System.out.println("发送设备列表到前端: " + deviceListJson);
|
|
// session.getBasicRemote().sendText(deviceListJson);
|
|
// } catch (IOException e) {
|
|
// e.printStackTrace();
|
|
// }
|
|
}
|
|
|
|
@OnMessage
|
|
public void onMessage(String message, Session session) throws IOException {
|
|
System.out.println("收到消息: " + message);
|
|
// 可以根据前端需求,在这里处理命令(比如刷新设备列表)
|
|
if ("refreshDevices".equals(message)) {
|
|
// String deviceListJson = Main.getAllDevicesJson();
|
|
// session.getBasicRemote().sendText(deviceListJson);
|
|
} else {
|
|
session.getBasicRemote().sendText("服务器已收到: " + message);
|
|
}
|
|
}
|
|
|
|
@OnClose
|
|
public void onClose(Session session) {
|
|
sessions.remove(session);
|
|
System.out.println("WebSocket连接已关闭: " + session.getId());
|
|
}
|
|
|
|
public static void broadcast(String message) {
|
|
for (Session session : sessions) {
|
|
if (session.isOpen()) {
|
|
try {
|
|
session.getBasicRemote().sendText(message);
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|