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