@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;
    }
 @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(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);
   }
 }
 @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 void doTestWriteTimeoutClient(boolean setTimeoutOnContainer) 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(BlockingConfig.class.getName(), false));
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();

    // Set the async timeout
    if (setTimeoutOnContainer) {
      wsContainer.setAsyncSendTimeout(TIMEOUT_MS);
    }

    tomcat.start();

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

    if (!setTimeoutOnContainer) {
      wsSession.getAsyncRemote().setSendTimeout(TIMEOUT_MS);
    }

    long lastSend = 0;

    // Should send quickly until the network buffers fill up and then block
    // until the timeout kicks in
    Exception exception = null;
    try {
      while (true) {
        Future<Void> f = wsSession.getAsyncRemote().sendBinary(ByteBuffer.wrap(MESSAGE_BINARY_4K));
        lastSend = System.currentTimeMillis();
        f.get();
      }
    } catch (Exception e) {
      exception = e;
    }

    long timeout = System.currentTimeMillis() - lastSend;

    String msg = "Time out was [" + timeout + "] ms";

    // Check correct time passed
    Assert.assertTrue(msg, timeout >= TIMEOUT_MS - MARGIN);

    // Check the timeout wasn't too long
    Assert.assertTrue(msg, timeout < TIMEOUT_MS * 2);

    Assert.assertNotNull(exception);
  }
Ejemplo n.º 6
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();
      }
    }
Ejemplo n.º 7
0
  @OnOpen
  public void open(Session session) {
    peers.add(session);
    Tweet tweet = new Tweet();
    tweet.setAuthor("THE SERVER");
    tweet.setMessage("Welcome! We will provide you with data " + "as soon as we have it available");
    List<Tweet> tweets = Arrays.asList(tweet);
    session.getAsyncRemote().sendText(Tweet.listToJsonArray(tweets).toString());

    logger.info("opened session with id " + session.getId());
  }
Ejemplo n.º 8
0
    @Override
    public void onOpen(Session session, EndpointConfig config) {
      session.getAsyncRemote().sendBinary(ByteBuffer.wrap(bytes));
      session.addMessageHandler(
          new MessageHandler.Whole<byte[]>() {

            @Override
            public void onMessage(byte[] message) {
              responses.add(message);
            }
          });
    }
    @Override
    public void onOpen(Session session, EndpointConfig config) {
      session.getAsyncRemote().sendText("Stuart");
      session.addMessageHandler(
          new MessageHandler.Whole<String>() {

            @Override
            public void onMessage(String message) {
              responses.add(message);
            }
          });
    }
Ejemplo n.º 10
0
  /**
   * Notifies the specified timeline message to browsers.
   *
   * @param message the specified message, for example
   *     <pre>
   * {
   *     "type": "article",
   *     "content": ""
   * }
   * </pre>
   */
  public static void notifyTimeline(final JSONObject message) {
    final String msgStr = message.toString();

    final Iterator<Session> i = SESSIONS.iterator();
    while (i.hasNext()) {
      final Session session = i.next();

      if (session.isOpen()) {
        session.getAsyncRemote().sendText(msgStr);
      }
    }
  }
Ejemplo n.º 11
0
 @Override
 public boolean asyncPush(String sid, String message) {
   boolean result = false;
   Session session = this.savedSessionMap.get(sid);
   if (session != null && session.isOpen()) {
     result = true;
     session.getAsyncRemote().sendText(message);
     this.logger.debug("websocket-push message:{},{}", sid, message);
   } else {
     this.logger.debug("websocket-push message:sid:{} not exist or closed", sid);
   }
   return result;
 }
Ejemplo n.º 12
0
    @Override
    public void send(String content) {
      Session session;
      synchronized (this) {
        session = _session;
      }
      try {
        if (session == null) throw new IOException("Unconnected");

        // Blocking sends for the client, using
        // AsyncRemote to allow concurrent sends.
        session.getAsyncRemote().sendText(content).get();
      } catch (Throwable x) {
        fail(x, "Exception");
      }
    }
Ejemplo n.º 13
0
  private void broadcastMessage(final Message serverMsg, final boolean includeThis) {
    final Gson gson = new Gson();

    try {
      final String jsonStr = gson.toJson(serverMsg);

      for (Session session : thisSession.getOpenSessions()) {
        if (!includeThis && thisSession.equals(session)) {
          continue;
        }
        session.getAsyncRemote().sendText(jsonStr);
      }
    } catch (Exception e) {
      LOG.error(e);
    }
  }
Ejemplo n.º 14
0
 /**
  * deprecated: 发送数据方法,根据session的hashcode找对应sess客户端
  *
  * <p>并发送数据,发送完return
  *
  * <p>date 2015-03-08
  *
  * @author sharkTang
  * @param session
  * @param closeReason
  */
 private void sendData() {
   if (null != webSessionMap && webSessionMap.size() > 0) {
     Session sess = webSessionMap.get(webSocketHashCodeStatic);
     // System.out.println(sess.getQueryString());
     try {
       if (null != sess && sess.isOpen()) {
         // sessionsStatic =
         // PuFaBigPingWebSocketServer.daPingWebsocketSession;
         sess.getAsyncRemote().sendText(sendDataStatic);
         //					if (sendDataStatic.length() <= 0) {
         //						sendDataStatic = WebSocketConstants.SPACESTR_ENG;
         //
         //					}
       }
     } catch (Exception ex) {
       logger_.info(sess.hashCode() + " 客户端发送数据异常,异常信息:" + ex.getMessage());
     }
   }
 }
  public synchronized void sendMessage(final String message) {

    /*
     * if Packet is bigger than 1000 Send the message through of sendDividedChain
     */
    if (message.length() > 1000) {

      try {
        sendDividedChain(message);
      } catch (Exception e) {
        e.printStackTrace();
      }

    } else {

      if (clientConnection != null && clientConnection.isOpen())
        clientConnection.getAsyncRemote().sendText(message);
    }
  }
Ejemplo n.º 16
0
  /**
   * 接受客户端的消息,并把消息发送给连接的会
   *
   * @param message 客户端发来的消息 *
   * @param session 客户端的会话
   */
  @OnMessage
  public void getMessage(String message, Session session) {

    for (Session openSession : session.getOpenSessions()) {
      /// System.out.println(message);
      System.out.println(message.split(":")[0]);
      // 利用键主键的方式获取到消息体为昵称:内容
      // message=message.split(":")[0]+ DATE_FORMAT.format(new
      // Date())+"</br>"+message.split(":")[1];
      Map result = new HashMap<String, Object>();
      result.put("nickName", message.split(":")[0]);
      result.put("time", DATE_FORMAT.format(new Date()));
      result.put("message", message.split(":")[1]);
      messageList.add(result);
      if (!openSession.equals(session)) {
        openSession.getAsyncRemote().sendText(JsonKit.toJson(result, 2));
      }
    }
  }
Ejemplo n.º 17
0
    @Override
    public void onOpen(Session session, EndpointConfig EndpointConfig) {
      try {
        session.addMessageHandler(
            new MessageHandler.Whole<Integer>() {
              @Override
              public void onMessage(Integer buf) {
                receivedLatch.countDown();
              }
            });

        for (int i = 0; i < noMessages; i++) {
          Future future = session.getAsyncRemote().sendObject(i);
          future.get();
          sentLatch.countDown();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
Ejemplo n.º 18
0
  @OnError
  public void errorHandle(Session session, Throwable error) {
    if (session != null && session.isOpen()) {
      WebsocketMessageWrapper<Error> response = new WebsocketMessageWrapper<>();
      response.setType(WebsocketMessageType.CUSTOMER_ERROR);
      response.setData(new Error());
      if (error instanceof CustomerNotFoundException) {
        response.setSequenceId(((CustomerNotFoundException) error).getSequenceId());
        response.getData().setCode("customer.notFound");
        response.getData().setDescription("Customer not found");
      } else {
        WebSocketServerLogger.LOG.handleWebsocketServerError(error);

        response.setSequenceId(UUID.randomUUID().toString());
        response.getData().setCode(error.getClass().getName());
        response.getData().setDescription("Handled exception");
      }

      session.getAsyncRemote().sendObject(response);
    }
  }
Ejemplo n.º 19
0
 @Override
 protected void send(
     Session session,
     String content,
     final TransportListener listener,
     final Mutable... messages) {
   session
       .getAsyncRemote()
       .sendText(
           content,
           new SendHandler() {
             @Override
             public void onResult(SendResult result) {
               Throwable failure = result.getException();
               if (failure != null) {
                 complete(messages);
                 disconnect("Exception");
                 listener.onFailure(failure, messages);
               }
             }
           });
 }
Ejemplo n.º 20
0
 @Override
 public void run() {
   session.getAsyncRemote().sendText("Hello " + counter.getAndIncrement());
 }
Ejemplo n.º 21
0
  /**
   * (non-javadoc)
   *
   * @see PackageProcessor#processingPackage(Session, Package)
   */
  @Override
  public void processingPackage(Session session, Package packageReceived) {

    LOG.info("Processing new package received");

    String channelIdentityPrivateKey = getChannel().getChannelIdentity().getPrivateKey();
    String destinationIdentityPublicKey =
        (String) session.getUserProperties().get(HeadersAttName.CPKI_ATT_HEADER_NAME);
    NodeProfile nodeProfile = null;
    AddNodeToCatalogMsjRespond addNodeToCatalogMsjRespond = null;

    try {

      AddNodeToCatalogMsgRequest messageContent =
          AddNodeToCatalogMsgRequest.parseContent(packageReceived.getContent());

      /*
       * Create the method call history
       */
      methodCallsHistory(
          getGson().toJson(messageContent.getNodeProfile()), destinationIdentityPublicKey);

      /*
       * Validate if content type is the correct
       */
      if (messageContent.getMessageContentType() == MessageContentType.JSON) {

        /*
         * Obtain the profile of the node
         */
        nodeProfile = messageContent.getNodeProfile();

        if (exist(nodeProfile)) {

          /*
           * Notify the node already exist
           */
          addNodeToCatalogMsjRespond =
              new AddNodeToCatalogMsjRespond(
                  CheckInProfileMsjRespond.STATUS.FAIL,
                  "The node profile already exist",
                  nodeProfile.getIdentityPublicKey());

        } else {

          /*
           * Insert NodesCatalog into data base
           */
          insertNodesCatalog(nodeProfile);

          /*
           * Insert NodesCatalogTransaction into data base
           */
          insertNodesCatalogTransaction(nodeProfile);

          /*
           * Insert NodesCatalogTransactionsPendingForPropagation into data base
           */
          insertNodesCatalogTransactionsPendingForPropagation(nodeProfile);

          /*
           * If all ok, respond whit success message
           */
          addNodeToCatalogMsjRespond =
              new AddNodeToCatalogMsjRespond(
                  CheckInProfileMsjRespond.STATUS.SUCCESS,
                  CheckInProfileMsjRespond.STATUS.SUCCESS.toString(),
                  nodeProfile.getIdentityPublicKey());
        }

        Package packageRespond =
            Package.createInstance(
                addNodeToCatalogMsjRespond.toJson(),
                packageReceived.getNetworkServiceTypeSource(),
                PackageType.ADD_NODE_TO_CATALOG_RESPOND,
                channelIdentityPrivateKey,
                destinationIdentityPublicKey);

        /*
         * Send the respond
         */
        session.getAsyncRemote().sendObject(packageRespond);
      }

    } catch (Exception exception) {

      try {

        LOG.error(exception.getMessage());

        /*
         * Respond whit fail message
         */
        addNodeToCatalogMsjRespond =
            new AddNodeToCatalogMsjRespond(
                AddNodeToCatalogMsjRespond.STATUS.FAIL,
                exception.getLocalizedMessage(),
                nodeProfile.getIdentityPublicKey());
        Package packageRespond =
            Package.createInstance(
                addNodeToCatalogMsjRespond.toJson(),
                packageReceived.getNetworkServiceTypeSource(),
                PackageType.ADD_NODE_TO_CATALOG_RESPOND,
                channelIdentityPrivateKey,
                destinationIdentityPublicKey);

        /*
         * Send the respond
         */
        session.getAsyncRemote().sendObject(packageRespond);

      } catch (Exception e) {
        LOG.error(e.getMessage());
      }
    }
  }
Ejemplo n.º 22
0
 @OnMessage
 public void onMessage(short s) throws IOException {
   String msg = Short.toString(s);
   session.getAsyncRemote().sendText(msg);
 }