2017-04-19 217 views
1

我正在建立一個websocket應用程序使用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); 
     } 
    } 

} 

如何接收事件後,將消息發送給客戶?我應該實例化我的班級服務器嗎?

回答

0

即使世界上HOWTO一個例子將消息發送到所有連接的客戶端在這個白板應用: 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); 
     } 
    } 
} 
相關問題