我正在使用 glassfish 构建一个 websocket 应用程序,我需要在给定事件中我的服务器向所有连接的客户端发送消息。我可以从两者发送和接收消息,但无法使用类服务器发送消息。
我的服务器类具有以下主体:
@ApplicationScoped
@ServerEndpoint("/actions")
公共(public)类DeviceWebSocketServer {
@Inject
private DeviceSessionHandler sessionHandler;
@OnOpen
public void open(Session session) {
sessionHandler.addSession(session);
}
@OnClose
public void close(Session session) {
sessionHandler.removeSession(session);
}
@OnError
public void onError(Throwable error) {
Logger.getLogger(DeviceWebSocketServer.class.getName()).log(Level.SEVERE, null, error);
}
@OnMessage
public void handleMessage(String message, Session session) {
System.out.println("Chegou uma mensagem: " + message);
System.out.println("Na sessao: " + session.getId());
try (JsonReader reader = Json.createReader(new StringReader(message))) {
JsonObject jsonMessage = reader.readObject();
if ("add".equals(jsonMessage.getString("action"))) {
Device device = new Device();
device.setName(jsonMessage.getString("name"));
device.setDescription(jsonMessage.getString("description"));
device.setType(jsonMessage.getString("type"));
device.setStatus("Off");
sessionHandler.addDevice(device);
}
if ("remove".equals(jsonMessage.getString("action"))) {
int id = (int) jsonMessage.getInt("id");
sessionHandler.removeDevice(id);
}
if ("toggle".equals(jsonMessage.getString("action"))) {
int id = (int) jsonMessage.getInt("id");
sessionHandler.toggleDevice(id);
}
}
}
收到事件后如何向客户发送消息?我应该实例化我的类服务器吗?
最佳答案
有一个关于如何在此白板应用程序中向所有连接的客户端发送消息的示例: https://netbeans.org/kb/docs/javaee/maven-websocketapi.html
@ServerEndpoint(value="/whiteboardendpoint", encoders = {FigureEncoder.class}, decoders = {FigureDecoder.class})
public class MyWhiteboard {
private static Set<Session> peers = Collections.synchronizedSet(new HashSet<Session>());
@OnMessage
public void broadcastFigure(Figure figure, Session session) throws IOException, EncodeException {
System.out.println("broadcastFigure: " + figure);
for (Session peer : peers) {
if (!peer.equals(session)) {
peer.getBasicRemote().sendObject(figure);
}
}
}
关于java - 从服务器发送消息到 websocket 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43496880/