【问题标题】:Send messages from server to websocket clients从服务器发送消息到 websocket 客户端
【发布时间】:2017-09-15 18:01:36
【问题描述】:

我正在使用 glassfish 构建一个 websocket 应用程序,我需要在给定事件中我的服务器向所有连接的客户端发送消息。我可以从两者发送和接收消息,但我无法使用类服务器发送消息。

我的服务器类具有以下主体:

@ApplicationScoped @ServerEndpoint("/actions") public class 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);
        }
    }

}

收到活动后如何向客户发送消息?我应该实例化我的类服务器吗?

【问题讨论】:

    标签: java websocket glassfish


    【解决方案1】:

    在这个白板应用程序中有一个关于如何向所有连接的客户端发送消息的示例: 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);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-07-15
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-10
      • 2017-01-12
      • 2013-04-01
      相关资源
      最近更新 更多