Exemplo n.º 1
0
  public static void manageIfException(
      WebSocketSession session, String methodName, ExceptionMethodWrapper method) {
    try {
      method.exec();
    } catch (Throwable t) {
      log.error(t.getMessage(), t);
      InternalErrorCodes iec;

      if (t instanceof AppException) {
        AppException ae = (AppException) t;
        iec = ae.getErrorCode();
      } else {
        iec = InternalErrorCodes.UNHANDLED_ERROR;
      }

      Response resp =
          new Response.ResponseBuilder<>(methodName)
              .status(iec.getStatus().intValue())
              .error(new AppError(iec.getMessage(), t.getMessage(), iec.getCode()))
              .build();

      try {
        session.sendMessage(new TextMessage(resp.toJsonStr()));
      } catch (Exception e) {
        log.error(e.getMessage(), e);
      }
    }
  }
 /** 给特定的在线用户发送消息 */
 public void sendMessageToUsers(ArrayList<Long> userIdList, TextMessage message) {
   if (userIdList == null) {
     return;
   }
   int listSize = userIdList.size();
   if (listSize == 0) {
     return;
   }
   int i = 0;
   for (WebSocketSession user : users) {
     try {
       if (user.getAttributes().get("USER_ID") != null) {
         if (user.isOpen() && userIdList.contains(user.getAttributes().get("USER_ID"))) {
           user.sendMessage(message);
           i++;
           if (listSize == i) {
             break;
           }
         }
       }
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
 private synchronized void sendMessage(WebSocketSession session, TextMessage message) {
   try {
     session.sendMessage(message);
   } catch (IOException e) {
     log.error("Exception sending message", e);
   }
 }
 /** 处理会话 */
 @Override
 public void handleMessage(WebSocketSession session, WebSocketMessage<?> message)
     throws Exception {
   // TODO Auto-generated method stub
   Map<String, String> select = JsonUtil.jsonToMap(message.getPayload().toString());
   String result = webSocketService.getNewMessage(select);
   session.sendMessage(new TextMessage(result.toString()));
   WebSocketCache.putMemberSession(select.get("userId"), session);
 }
Exemplo n.º 5
0
 private void sendError(WebSocketSession session, String message) {
   try {
     JsonObject response = new JsonObject();
     response.addProperty("id", "error");
     response.addProperty("message", message);
     session.sendMessage(new TextMessage(response.toString()));
   } catch (IOException e) {
     log.error("Exception sending message", e);
   }
 }
 /** 给所有在线用户发送消息 */
 public void sendMessageToUsers(TextMessage message) {
   for (WebSocketSession user : users) {
     try {
       if (user.isOpen()) {
         user.sendMessage(message);
       }
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {

      StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT);
      headers.setAcceptVersion("1.1,1.2");
      headers.setHeartbeat(0, 0);
      Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();

      TextMessage textMessage = new TextMessage(new String(this.encoder.encode(message), UTF_8));
      session.sendMessage(textMessage);
    }
 @Override
 protected void handleTextMessage(WebSocketSession session, TextMessage message) {
   List<WebSocketSession> sessions = Sessions.getSessions();
   for (WebSocketSession webSocketSession : sessions) {
     try {
       webSocketSession.sendMessage(new TextMessage(message.getPayload()));
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
 @Test
 public void fallbackAfterTransportFailure() throws Exception {
   this.testFilter.sendErrorMap.put("/websocket", 200);
   this.testFilter.sendErrorMap.put("/xhr_streaming", 500);
   TestClientHandler handler = new TestClientHandler();
   initSockJsClient(createWebSocketTransport(), createXhrTransport());
   WebSocketSession session = this.sockJsClient.doHandshake(handler, this.baseUrl + "/echo").get();
   assertEquals("Fallback didn't occur", XhrClientSockJsSession.class, session.getClass());
   TextMessage message = new TextMessage("message1");
   session.sendMessage(message);
   handler.awaitMessage(message, 5000);
 }
Exemplo n.º 10
0
  private void sendMessage(final WebSocketSession session, final TextMessage textMessage) {

    this.taskExecutor.execute(
        () -> {
          if (session.isOpen()) {
            try {
              session.sendMessage(textMessage);
            } catch (IOException e) {
              logger.error("sendMessage to session", e);
            }
          }
        });
  }
Exemplo n.º 11
0
  private void start(final WebSocketSession session, JsonObject jsonMessage) {
    try {
      // Media Logic (Media Pipeline and Elements)
      UserSession user = new UserSession();
      MediaPipeline pipeline = kurento.createMediaPipeline();
      user.setMediaPipeline(pipeline);
      WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).build();
      user.setWebRtcEndpoint(webRtcEndpoint);
      users.put(session.getId(), user);

      webRtcEndpoint.addOnIceCandidateListener(
          new EventListener<OnIceCandidateEvent>() {

            @Override
            public void onEvent(OnIceCandidateEvent event) {
              JsonObject response = new JsonObject();
              response.addProperty("id", "iceCandidate");
              response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
              try {
                synchronized (session) {
                  session.sendMessage(new TextMessage(response.toString()));
                }
              } catch (IOException e) {
                log.debug(e.getMessage());
              }
            }
          });

      mouth = new NuboMouthDetector.Builder(pipeline).build();

      webRtcEndpoint.connect(mouth);
      mouth.connect(webRtcEndpoint);

      // SDP negotiation (offer and answer)
      String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
      String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer);

      // Sending response back to client
      JsonObject response = new JsonObject();
      response.addProperty("id", "startResponse");
      response.addProperty("sdpAnswer", sdpAnswer);

      synchronized (session) {
        session.sendMessage(new TextMessage(response.toString()));
      }
      webRtcEndpoint.gatherCandidates();

    } catch (Throwable t) {
      sendError(session, t.getMessage());
    }
  }
  private <P, R> Response<R> sendRequestWebSocket(Request<P> request, Class<R> resultClass) {

    log.info("Req-> {}", request.toString());

    Future<Response<JsonElement>> responseFuture = null;

    if (request.getId() != null) {
      responseFuture = pendingRequests.prepareResponse(request.getId());
    }

    try {
      synchronized (wsSession) {
        wsSession.sendMessage(new TextMessage(JsonUtils.toJson(request)));
      }
    } catch (Exception e) {
      throw new KurentoException(
          "Exception while sending message '"
              + JsonUtils.toJson(request)
              + "' to websocket with native sessionId '"
              + wsSession.getId()
              + "'",
          e);
    }

    if (responseFuture == null) {
      return null;
    }

    Response<JsonElement> responseJsonObject;
    try {
      responseJsonObject = responseFuture.get(TIMEOUT, TimeUnit.MILLISECONDS);

      log.info("<-Res {}", responseJsonObject.toString());

    } catch (InterruptedException e) {
      // TODO What to do in this case?
      throw new JsonRpcException("Interrupted while waiting for a response", e);
    } catch (ExecutionException e) {
      // TODO Is there a better way to handle this?
      throw new JsonRpcException("This exception shouldn't be thrown", e);
    } catch (TimeoutException e) {
      throw new TransportException(
          "Timeout of "
              + TIMEOUT
              + " milliseconds waiting from response to request with id:"
              + request.getId(),
          e);
    }

    return MessageUtils.convertResponse(responseJsonObject, resultClass);
  }
 @Test(timeout = 5000)
 public void fallbackAfterConnectTimeout() throws Exception {
   TestClientHandler clientHandler = new TestClientHandler();
   this.testFilter.sleepDelayMap.put("/xhr_streaming", 10000L);
   this.testFilter.sendErrorMap.put("/xhr_streaming", 503);
   initSockJsClient(createXhrTransport());
   this.sockJsClient.setConnectTimeoutScheduler(this.wac.getBean(ThreadPoolTaskScheduler.class));
   WebSocketSession clientSession =
       sockJsClient.doHandshake(clientHandler, this.baseUrl + "/echo").get();
   assertEquals("Fallback didn't occur", XhrClientSockJsSession.class, clientSession.getClass());
   TextMessage message = new TextMessage("message1");
   clientSession.sendMessage(message);
   clientHandler.awaitMessage(message, 5000);
   clientSession.close();
 }
  /** 连接成功 */
  @Override
  public void afterConnectionEstablished(WebSocketSession session) throws Exception {

    // TODO Auto-generated method stub

    System.out.println(session);

    Map<String, String> select = new HashMap<String, String>();
    String userId = (String) session.getAttributes().get("userId");
    String userPwd = (String) session.getAttributes().get("userPwd");
    select.put("userId", userId);
    select.put("userPwd", userPwd);
    String result = webSocketService.getNewMessage(select);
    session.sendMessage(new TextMessage(result.toString()));
    WebSocketCache.putMemberSession(select.get("userId"), session);
  }
 private void testEcho(int messageCount, Transport transport, WebSocketHttpHeaders headers)
     throws Exception {
   List<TextMessage> messages = new ArrayList<>();
   for (int i = 0; i < messageCount; i++) {
     messages.add(new TextMessage("m" + i));
   }
   TestClientHandler handler = new TestClientHandler();
   initSockJsClient(transport);
   URI url = new URI(this.baseUrl + "/echo");
   WebSocketSession session = this.sockJsClient.doHandshake(handler, headers, url).get();
   for (TextMessage message : messages) {
     session.sendMessage(message);
   }
   handler.awaitMessageCount(messageCount, 5000);
   for (TextMessage message : messages) {
     assertTrue("Message not received: " + message, handler.receivedMessages.remove(message));
   }
   assertEquals(
       "Remaining messages: " + handler.receivedMessages, 0, handler.receivedMessages.size());
   session.close();
 }
 @Override
 public void notifyBallotResult(BallotResult ballotResult, String data) {
   // Send this to all appropriate watchers
   // For now we can iterate the values in the hashmap but we need to store a reverse map
   // of ids to sessions.
   Iterator<Map.Entry<WebSocketSession, Long>> i = sessions.entrySet().iterator();
   while (i.hasNext()) {
     Map.Entry<WebSocketSession, Long> entry = i.next();
     // does it match the ballot we have just updated
     if (entry.getValue() == ballotResult.getBallot().getId()) {
       // We have a match, so send update to watcher
       WebSocketSession session = entry.getKey();
       try {
         session.sendMessage(new TextMessage(data));
       } catch (IOException e) {
         // remove from current map
         i.remove();
       }
     }
   }
 }
Exemplo n.º 17
0
 @Override
 protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
   Object cookies = session.getAttributes().get(HttpHeaders.COOKIE);
   log.info("cookies: {}; message: {}", cookies, message);
   session.sendMessage(message);
 }
 /**
  * 给某个用户发送消息
  *
  * @param userName
  * @param message
  * @throws IOException
  */
 public void sendMessageToUser(Long uid, TextMessage message) throws IOException {
   WebSocketSession session = userSocketSessionMap.get(uid);
   if (session != null && session.isOpen()) {
     session.sendMessage(message);
   }
 }
Exemplo n.º 19
0
 @Override
 protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
   super.handleTextMessage(session, message);
   TextMessage returnMessage = new TextMessage(message.getPayload() + " received at server");
   session.sendMessage(returnMessage);
 }
 @Override
 public void afterConnectionEstablished(WebSocketSession session) throws Exception {
   for (TextMessage message : this.messagesToSend) {
     session.sendMessage(message);
   }
 }
Exemplo n.º 21
0
 public static void sendMessage(WebSocketSession session, String message) throws IOException {
   session.sendMessage(new TextMessage(message));
 }
 @Override
 protected void handleTextMessage(WebSocketSession session, TextMessage message)
     throws Exception {
   session.sendMessage(message);
 }