Example #1
0
  @Test
  public void testEcho() throws IOException, DeploymentException, InterruptedException {
    Server server = startServer(SessionBuilderTestEndpoint.class);

    CountDownLatch messageLatch = new CountDownLatch(1);

    try {
      Session session =
          new SessionBuilder()
              .uri(getURI(SessionBuilderTestEndpoint.class))
              .messageHandler(
                  String.class,
                  message -> {
                    if (MESSAGE.equals(message)) {
                      messageLatch.countDown();
                    }
                  })
              .connect();

      session.getBasicRemote().sendText(MESSAGE);

      assertTrue(messageLatch.await(3, TimeUnit.SECONDS));
    } finally {
      stopServer(server);
    }
  }
Example #2
0
  @Test
  public void testEncoderDecoder()
      throws IOException, DeploymentException, InterruptedException, EncodeException {
    Server server = startServer(SessionBuilderEncDecTestEndpoint.class);

    CountDownLatch messageLatch = new CountDownLatch(1);

    final ClientEndpointConfig clientEndpointConfig =
        ClientEndpointConfig.Builder.create()
            .encoders(Collections.singletonList(AClassCoder.class))
            .decoders(Collections.singletonList(AClassCoder.class))
            .build();

    try {
      Session session =
          new SessionBuilder()
              .uri(getURI(SessionBuilderEncDecTestEndpoint.class))
              .clientEndpointConfig(clientEndpointConfig)
              .messageHandler(
                  AClass.class,
                  aClass -> {
                    if (MESSAGE.equals(aClass.toString())) {
                      messageLatch.countDown();
                    }
                  })
              .connect();

      session.getBasicRemote().sendObject(new AClass());

      assertTrue(messageLatch.await(3, TimeUnit.SECONDS));
    } finally {
      stopServer(server);
    }
  }
Example #3
0
  @Test
  public void testEchoPartial() throws IOException, DeploymentException, InterruptedException {
    Server server = startServer(SessionBuilderTestEndpoint.class);

    CountDownLatch messageLatch = new CountDownLatch(1);

    try {
      Session session =
          new SessionBuilder()
              .uri(getURI(SessionBuilderTestEndpoint.class))
              .messageHandlerPartial(
                  String.class,
                  (message, complete) -> {
                    System.out.println("partial: " + message + " " + complete);

                    if (MESSAGE.equals(message) && complete) {
                      messageLatch.countDown();
                    }
                  })
              .connect();

      session.getBasicRemote().sendText(MESSAGE);

      assertTrue(messageLatch.await(30000000, TimeUnit.SECONDS));
    } finally {
      stopServer(server);
    }
  }
 public void sendData(ResponseDTO resp, String sessionID) throws IOException, Exception {
   for (Session session : peers) {
     if (sessionID.equals(session.getId())) {
       session.getBasicRemote().sendBinary(getZippedResponse(resp));
     }
   }
 }
  /**
   * @param gd
   * @param peer
   * @throws IOException
   * @throws EncodeException
   * @throws JSONException
   */
  @OnMessage
  public void broadCastMessage(GameData gd, Session peer)
      throws IOException, EncodeException, JSONException, Exception {
    System.out.println("JSON RECEIVED");
    String gameID = gd.getJson().get("gameId").toString();
    String playername = gd.getJson().getString("playerName");

    // we may not need these lines
    GameBoard board = cache.getBoard();
    board.addPlayerToBoard(new Player(playername));
    JSONObject jSONObject = new JSONObject();
    jSONObject.put("players", board.getPlayersOnBoard());
    jSONObject.put("gameId", gameID);
    jSONObject.put("type", "notify");
    jSONObject.put("playerName", playername);
    if (board.getPlayersOnBoard().size() == 3) {
      jSONObject.put("startGame", true);
    }
    gd.setJson(jSONObject);
    System.out.println("JSON : " + gd.getJson());
    for (Session currPeer : peers) {
      currPeer.getBasicRemote().sendObject(gd);
    }
    System.out.println("JSON SENT");
  }
Example #6
0
  @Test
  public void testLimits() throws DeploymentException {
    Server server = startServer(PingPongEndpoint.class);

    try {

      ClientManager client = createClient();
      final Session session =
          client.connectToServer(
              new Endpoint() {
                @Override
                public void onOpen(Session session, EndpointConfig config) {
                  // do nothing.
                }
              },
              ClientEndpointConfig.Builder.create().build(),
              getURI(PingPongEndpoint.class));

      session
          .getBasicRemote()
          .sendPing(
              ByteBuffer.wrap(
                  "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345"
                      .getBytes()));
      try {
        session
            .getBasicRemote()
            .sendPing(
                ByteBuffer.wrap(
                    "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456"
                        .getBytes()));
        fail();
      } catch (IllegalArgumentException e) {
        // ignore
      }
      session
          .getBasicRemote()
          .sendPong(
              ByteBuffer.wrap(
                  "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345"
                      .getBytes()));
      try {
        session
            .getBasicRemote()
            .sendPong(
                ByteBuffer.wrap(
                    "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456"
                        .getBytes()));
        fail();
      } catch (IllegalArgumentException e) {
        // ignore
      }

    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e.getMessage(), e);
    } finally {
      stopServer(server);
    }
  }
Example #7
0
  @Override
  public void run() {

    try {
      while (shouldIRun) {
        Thread.sleep(crunchifyRunEveryNSeconds);
        long fileLength = crunchifyFile.length();
        if (fileLength > lastKnownPosition) {

          // Reading and writing file
          RandomAccessFile readWriteFileAccess = new RandomAccessFile(crunchifyFile, "rw");
          readWriteFileAccess.seek(lastKnownPosition);
          String crunchifyLine = null;
          while ((crunchifyLine = readWriteFileAccess.readLine()) != null) {
            for (Session s : AppLogView.sessions) {
              // s.getAsyncRemote().sendText(crunchifyLine);
              s.getBasicRemote().sendText(crunchifyLine);
            }
          }
          lastKnownPosition = readWriteFileAccess.getFilePointer();
          readWriteFileAccess.close();
        }
      }
    } catch (Exception e) {
      shouldIRun = false;
    }
  }
Example #8
0
  @Test
  public void testBug58232() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(Bug54807Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();

    tomcat.start();

    Assert.assertEquals(LifecycleState.STARTED, ctx.getState());

    SimpleClient client = new SimpleClient();
    URI uri = new URI("ws://localhost:" + getPort() + "/echoBasic");

    try (Session session = wsContainer.connectToServer(client, uri); ) {
      CountDownLatch latch = new CountDownLatch(1);
      BasicText handler = new BasicText(latch);
      session.addMessageHandler(handler);
      session.getBasicRemote().sendText("echoBasic");

      boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
      Assert.assertTrue(latchResult);

      Queue<String> messages = handler.getMessages();
      Assert.assertEquals(1, messages.size());
      for (String message : messages) {
        Assert.assertEquals("echoBasic", message);
      }
    }
  }
  private void doMaxMessageSize(String path, long size, boolean expectOpen) throws Exception {

    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(
        new ApplicationListener(TesterEchoServer.Config.class.getName(), false));
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();

    Session s = connectToEchoServer(wsContainer, EndpointA.class, path);

    StringBuilder msg = new StringBuilder();
    for (long i = 0; i < size; i++) {
      msg.append('x');
    }

    s.getBasicRemote().sendText(msg.toString());

    // Wait for up to 5 seconds for session to close
    boolean open = s.isOpen();
    int count = 0;
    while (open != expectOpen && count < 50) {
      Thread.sleep(100);
      count++;
      open = s.isOpen();
    }

    Assert.assertEquals(Boolean.valueOf(expectOpen), Boolean.valueOf(s.isOpen()));
  }
  // onMessage will be called by WebSockets when this connection has received
  // a WebSocket message from the other side of the connection.
  // The message is derived from the WebSocket frame payloads of one, and only one, WebSocket
  // message.
  @Override
  public void onMessage(String message) {
    try {
      count++;

      if (message.toLowerCase().equals("stop")) {
        // send a WebSocket message back to the other endpoint that says we will stop.
        currentSession.getBasicRemote().sendText("OK. I will stop.");

        // Sleep to let the other side get the message before stopping - a bit kludgy, but this is
        // just a sample!
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
        }

        currentSession.close();
      } else {
        // send the message back to the other side with the iteration count.  Notice we can send
        // multiple message without having
        // to receive messages in between.
        currentSession
            .getBasicRemote()
            .sendText("From: " + this.getClass().getSimpleName() + "  Iteration count: " + count);
        currentSession.getBasicRemote().sendText(message);
      }

    } catch (IOException ex) {
      // no error processing will be done for this sample
    }
  }
Example #11
0
    @Override
    public void onOpen(Session session, EndpointConfig EndpointConfig) {
      try {
        session.addMessageHandler(
            new MessageHandler.Whole<Integer>() {
              @Override
              public void onMessage(Integer message) {
                receivedLatch.countDown();
              }
            });

        for (int i = 0; i < noMessages; i++) {
          session
              .getAsyncRemote()
              .sendObject(
                  i,
                  new SendHandler() {
                    @Override
                    public void onResult(SendResult result) {
                      if (result.isOK()) {
                        sentLatch.countDown();
                      }
                    }
                  });
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  @Test
  public void testConnectToServerEndpoint() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(
        new ApplicationListener(TesterEchoServer.Config.class.getName(), false));
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();
    Session wsSession =
        wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://localhost:" + getPort() + TesterEchoServer.Config.PATH_ASYNC));
    CountDownLatch latch = new CountDownLatch(1);
    BasicText handler = new BasicText(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText(MESSAGE_STRING_1);

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);

    Assert.assertTrue(latchResult);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(1, messages.size());
    Assert.assertEquals(MESSAGE_STRING_1, messages.peek());
  }
    @Override
    public void onOpen(Session session, EndpointConfig config) {

      // Reset everything
      timeout = -1;
      exception = null;
      running = true;

      if (!TestWsWebSocketContainer.timoutOnContainer) {
        session.getAsyncRemote().setSendTimeout(TIMEOUT_MS);
      }

      long lastSend = 0;

      // Should send quickly until the network buffers fill up and then
      // block until the timeout kicks in
      try {
        while (true) {
          lastSend = System.currentTimeMillis();
          Future<Void> f = session.getAsyncRemote().sendBinary(ByteBuffer.wrap(MESSAGE_BINARY_4K));
          f.get();
        }
      } catch (ExecutionException e) {
        exception = e;
      } catch (InterruptedException e) {
        exception = e;
      }
      timeout = System.currentTimeMillis() - lastSend;
      running = false;
    }
 /**
  * deprecated: 接收到客户端连接请求时调用
  *
  * <p>date 2015-03-06
  *
  * @author sharkTang
  * @param session
  */
 @OnOpen
 public void onOpen(Session session) {
   try {
     // 每次open一个session时,赋值到全局WebsocketSession,保持统一的全局session数据
     daPingWebsocketSession = session;
     webSocketMapAction(webSessionMap, session, WebSocketConstants.ADD_STR);
     // 往websocketManger添加一份数据
     WebSocketManager.webSocketClientCount++;
     WebSocketManager.webQueryStringSet.add(session.getQueryString());
     /*
      * 每创建一个连接,将session信息保存到全局HashMap Key: session的hashcode,
      * value:组装的sessionBo 并对全局Map数据加锁
      */
     WebSocketBo webSocketBo = new WebSocketBo();
     webSocketBo.setWsId(UUIDUtils.getUUID());
     webSocketBo.setMessageStatus(WebSocketConstants.MESSAGESTATUSNO); // 初始化时设为消息状态为no状态
     int webSocketHashCode = session.hashCode();
     webSocketBo.setWsHashCode(webSocketHashCode);
     String pageType = session.getQueryString();
     if (null == pageType) {
       pageType = WebSocketConstants.SPACESTR_ENG;
     }
     webSocketBo.setPageType(pageType);
     webSocketAction(webSocketMap, session, WebSocketConstants.ADD_STR, webSocketBo);
     // 发送初始化数据
     //	String sendDataString = DataInitServer.getNewInitData();
     //	session.getAsyncRemote().sendText(sendDataString);
   } catch (Exception e) {
   }
 }
Example #15
0
  private void unjoinChat() {
    if (thisSession.getUserProperties().containsKey("USER")) {
      LOG.debug("unjoinChat(): " + thisSession.getUserProperties().get("USER"));

      sessionService.removeOnSessionDestroyedListener(callback);

      if (isHttpSessionValid) {
        int sessionIdleTime =
            (int) ((System.currentTimeMillis() - httpSession.getLastAccessedTime()) / 1000);
        LOG.debug("Max idle timeout: " + (sessionIdleTime + defaultSessionTimeout));
        httpSession.setMaxInactiveInterval(sessionIdleTime + defaultSessionTimeout);
      }

      int userNb = usersLoggedIn.decrementAndGet();

      Message infoMsg = new Message();

      infoMsg.TYPE = "INFO";
      infoMsg.SUBTYPE = "JOIN";
      infoMsg.INFO_MSG = thisSession.getUserProperties().get("USER") + " has left the building";
      infoMsg.STATS_MSG = userNb + " User" + (userNb > 1 ? "s " : " ") + "online!";
      infoMsg.USER_LIST = buildUserList(false);

      thisSession.getUserProperties().clear();

      broadcastMessage(infoMsg, false);
    }
  }
 /**
  * @param message { type: nickname: invitationName: // receive: msg: muc: }
  * @param session
  */
 @OnMessage
 public String onMessage(String message, Session session) {
   String rs = null;
   JSONObject object = null;
   String sessionID = session.getId();
   object = new JSONObject(message);
   System.out.println("message---------" + object.toString() + "--" + session.getId());
   switch ((String) object.get("type")) {
     case "nickname":
       login(object, sessionID);
     case "empty":
       // System.out.println(new
       // Timestamp(System.currentTimeMillis())+"--HeartBeat--"+session.getId());
       break;
     case "create_muc":
       rs = createMuc(object, sessionID);
       break;
     case "invite":
       rs = invite(object, sessionID);
       break;
     case "msg":
       rs = msg(object, sessionID);
       break;
     case "receive": // 接受邀请
       rs = receive(object, sessionID);
       break;
     case "broadcast":
       rs = broadcast(object, sessionID);
       break;
     default:
       System.out.println("-------Do nothing");
       break;
   }
   return rs;
 }
 @OnMessage(maxMessageSize = 111222)
 public String echoText(String msg) {
   switch (msg) {
     case "text-max":
       return String.format("%,d", session.getMaxTextMessageBufferSize());
     case "binary-max":
       return String.format("%,d", session.getMaxBinaryMessageBufferSize());
     case "decoders":
       return join(config.getDecoders(), ", ");
     case "encoders":
       return join(config.getEncoders(), ", ");
     case "subprotocols":
       if (serverConfig == null) {
         return "<not a ServerEndpointConfig>";
       } else {
         List<String> protocols = new ArrayList<>();
         protocols.addAll(serverConfig.getSubprotocols());
         Collections.sort(protocols);
         return join(protocols, ", ");
       }
     case "configurator":
       if (serverConfig == null) {
         return "<not a ServerEndpointConfig>";
       } else {
         return serverConfig.getConfigurator().getClass().getName();
       }
     default:
       // normal echo
       return msg;
   }
 }
Example #18
0
  private void handleChat(final Message clientMsg) {
    Message broadcastMsg;

    if (clientMsg.SUBTYPE.equals("MSG")) {

      lastActivityTime = System.currentTimeMillis();

      ChatMsg chatMsg = new ChatMsg();
      broadcastMsg = clientMsg;
      // You can't trust nobody ;)
      chatMsg.MSG = clientMsg.CHAT_MSG.MSG.replace("<", "&lt;").replace("&", "&amp;");
      chatMsg.COLOR = (String) thisSession.getUserProperties().get("COLOR");
      chatMsg.FROM = (String) thisSession.getUserProperties().get("USER");

      ChatLog logMsg = new ChatLog();
      logMsg.setDate(new Date(lastActivityTime));
      logMsg.setUser(chatMsg.FROM);
      logMsg.setMessage(chatMsg.MSG);

      try {
        chatLogRepository.insert(logMsg);
      } catch (Exception e) {
        LOG.error(e.getMessage());
      }

      broadcastMsg.CHAT_MSG = chatMsg;
      broadcastMessage(broadcastMsg, true);
    }
  }
 private void updateUserList() {
   List<String> usernames = new ArrayList<>();
   for (Session s : session.getOpenSessions()) {
     String uname = (String) s.getUserProperties().get(USERNAME_KEY);
     usernames.add(uname);
   }
   this.endpointConfig.getUserProperties().put(USERNAMES_KEY, usernames);
 }
 @OnMessage
 public void onMessage(Double d) throws IOException {
   if (d == null) {
     session.getAsyncRemote().sendText("Error: Double is null");
   } else {
     String msg = String.format(Locale.US, "%.4f", d);
     session.getAsyncRemote().sendText(msg);
   }
 }
 @OnClose
 public void onClose(Session session) {
   System.out.println(session.getId() + "------has closed");
   // sess_map.remove(session.getId());
   AbstractXMPPConnection conn = conn_map.get(session.getId());
   conn.disconnect();
   sess_map.remove(session.getId());
   conn_map.remove(session.getId());
 }
 @OnMessage
 public void onMessage(Byte b) throws IOException {
   if (b == null) {
     session.getAsyncRemote().sendText("Error: Byte is null");
   } else {
     String msg = String.format("0x%02X", b);
     session.getAsyncRemote().sendText(msg);
   }
 }
 @OnMessage
 public void onMessage(Character c) throws IOException {
   if (c == null) {
     session.getAsyncRemote().sendText("Error: Character is null");
   } else {
     String msg = c.toString();
     session.getAsyncRemote().sendText(msg);
   }
 }
 private int getOpenCount(Set<Session> sessions) {
   int result = 0;
   for (Session session : sessions) {
     if (session.isOpen()) {
       result++;
     }
   }
   return result;
 }
  private void doTestWriteTimeoutServer(boolean setTimeoutOnContainer) throws Exception {

    /*
     * Note: There are all sorts of horrible uses of statics in this test
     *       because the API uses classes and the tests really need access
     *       to the instances which simply isn't possible.
     */
    timoutOnContainer = setTimeoutOnContainer;

    Tomcat tomcat = getTomcatInstance();

    if (getProtocol().equals(Http11Protocol.class.getName())) {
      // This will never work for BIO
      return;
    }

    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(new ApplicationListener(ConstantTxConfig.class.getName(), false));
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();

    tomcat.start();

    Session wsSession =
        wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://localhost:" + getPort() + ConstantTxConfig.PATH));

    wsSession.addMessageHandler(new BlockingBinaryHandler());

    int loops = 0;
    while (loops < 15) {
      Thread.sleep(1000);
      if (!ConstantTxEndpoint.getRunning()) {
        break;
      }
      loops++;
    }

    // Check the right exception was thrown
    Assert.assertNotNull(ConstantTxEndpoint.getException());
    Assert.assertEquals(ExecutionException.class, ConstantTxEndpoint.getException().getClass());
    Assert.assertNotNull(ConstantTxEndpoint.getException().getCause());
    Assert.assertEquals(
        SocketTimeoutException.class, ConstantTxEndpoint.getException().getCause().getClass());

    // Check correct time passed
    Assert.assertTrue(ConstantTxEndpoint.getTimeout() >= TIMEOUT_MS);

    // Check the timeout wasn't too long
    Assert.assertTrue(ConstantTxEndpoint.getTimeout() < TIMEOUT_MS * 2);
  }
 public static void encodeCommonReply(
     Session session, String token, String username, String text) {
   if (session.isOpen()) {
     try {
       session.getBasicRemote().sendText(token + DELIMITER + username + DELIMITER + text);
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
Example #27
0
 private void activeClose(CloseReason reason) {
   try {
     if (thisSession.isOpen()) {
       LOG.debug("Closing connection to peer: " + thisSession.getId());
       thisSession.close(reason);
     }
   } catch (IOException e) {
     LOG.error(e);
   }
 }
 @OnOpen
 public void open(Session session) {
   System.out.println("Opening client Session : " + session.getId());
   try {
     session.getBasicRemote().sendText("test");
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
 private void broadcastUserListUpdate() {
   UserListUpdateMessage ulum = new UserListUpdateMessage(this.getUserList());
   for (Session nextSession : session.getOpenSessions()) {
     try {
       nextSession.getBasicRemote().sendObject(ulum);
     } catch (IOException | EncodeException ex) {
       System.out.println("Error updating a client : " + ex.getMessage());
     }
   }
 }
Example #30
0
 private void sendTimeToAll(Session session) {
   allSessions = session.getOpenSessions();
   for (Session sess : allSessions) {
     try {
       sess.getBasicRemote().sendText("Local time: " + LocalTime.now().format(timeFormatter));
     } catch (IOException ioe) {
       System.out.println(ioe.getMessage());
     }
   }
 }