Java 类javax.websocket.OnMessage 实例源码

项目:websocket-chat    文件:ChatServer.java   
@OnMessage
public void msgReceived(ChatMessage msg, Session s) {
    if (msg.getMsg().equals(LOGOUT_MSG)) {
        try {
            s.close();
            return;
        } catch (IOException ex) {
            Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    Predicate<Session> filterCriteria = null;
    if (!msg.isPrivate()) {
        //for ALL (except self)
        filterCriteria = (session) -> !session.getUserProperties().get("user").equals(user);
    } else {
        String privateRecepient = msg.getRecepient();
        //private IM
        filterCriteria = (session) -> privateRecepient.equals(session.getUserProperties().get("user"));
    }

    s.getOpenSessions().stream()
            .filter(filterCriteria)
            //.forEach((session) -> session.getAsyncRemote().sendText(msgContent));
            .forEach((session) -> session.getAsyncRemote().sendObject(new Reply(msg.getMsg(), user, msg.isPrivate())));

}
项目:KITE    文件:ConfiguratorWsServlet.java   
@OnMessage
public String onMessage(String message) {
  List<String> splittedMessage = Arrays.asList(message.split(Pattern.quote("|")));
  switch (splittedMessage.get(0)) {
    case "configuration-name":
      this.configName = splittedMessage.get(1);
      break;
    case "callback":
      this.callback = splittedMessage.get(1);
      break;
  }
  if (log.isDebugEnabled())
    log.debug("Message from the client: " + message);
  return this.createConfigurationText();

}
项目:lams    文件:PresenceWebsocketServer.java   
/**
    * Receives a message sent by Learner via a websocket.
    *
    * @throws IOException
    */
   @OnMessage
   public void receiveRequest(String input, Session session) throws JSONException, IOException {
if (StringUtils.isBlank(input)) {
    return;
}
if (input.equalsIgnoreCase("ping")) {
    // just a ping every few minutes
    return;
}

JSONObject requestJSON = new JSONObject(input);
switch (requestJSON.getString("type")) {
    case "message":
    PresenceWebsocketServer.storeMessage(requestJSON, session);
    break;
    case "fetchConversation":
    PresenceWebsocketServer.sendConversation(requestJSON, session);
    break;
}
   }
项目:lams    文件:LearningWebsocketServer.java   
/**
    * Receives a message sent by Learner via a websocket.
    */
   @OnMessage
   public void receiveRequest(String input, Session websocket) throws JSONException {
if (StringUtils.isBlank(input)) {
    return;
}
if (input.equalsIgnoreCase("ping")) {
    // just a ping every few minutes
    return;
}

JSONObject requestJSON = new JSONObject(input);
switch (requestJSON.getString("type")) {
    case "vote":
    LearningWebsocketServer.vote(websocket);
    break;
    case "submitReport":
    LearningWebsocketServer.submitReport(requestJSON, websocket);
    break;
}
   }
项目:Hydrograph    文件:HydrographUiClientSocket.java   
/**
 * 
 * Called by web socket server, message contain execution tracking status that updated on job canvas.
 *
 * @param message the message
 * @param session the session
 */
@OnMessage
public void updateJobTrackingStatus(String message, Session session) { 

    final String status = message; 
    Display.getDefault().asyncExec(new Runnable() {
        public void run() {
            Gson gson = new Gson();
            ExecutionStatus executionStatus=gson.fromJson(status, ExecutionStatus.class);
            IWorkbenchPage page = PlatformUI.getWorkbench().getWorkbenchWindows()[0].getActivePage();
            IEditorReference[] refs = page.getEditorReferences();
            for (IEditorReference ref : refs){
                IEditorPart editor = ref.getEditor(false);
                if(editor instanceof ELTGraphicalEditor){
                    ELTGraphicalEditor editPart=(ELTGraphicalEditor)editor;
                    if(editPart.getJobId().equals(executionStatus.getJobId()) || (((editPart.getContainer()!=null) && 
                            (editPart.getContainer().getUniqueJobId().equals(executionStatus.getJobId()))) && editPart.getContainer().isOpenedForTracking() )){
                            TrackingStatusUpdateUtils.INSTANCE.updateEditorWithCompStatus(executionStatus, (ELTGraphicalEditor)editor,false);
                    }
                }
            }
        }
    });
}
项目:Hydrograph    文件:HydrographEngineCommunicatorSocket.java   
/**
 * Client onMessage get called to kill the job 
 * @param message
 * @param session
 */
@OnMessage
public void onMessage(String message, Session session) {
    logger.info("Trying to kill the job");
    final Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            if (execution != null) {
                logger.info("Job killed successfully");
                execution.kill();
                timer.cancel();
            }
        }

    };
    timer.schedule(task, 0l, 600);
}
项目:scalable-websocket-chat-with-hazelcast    文件:ChatServer.java   
@OnMessage
public void msgReceived(ChatMessage msg, Session s) {
    msg.from(user);
    if (msg.getMsg().equals(LOGOUT_MSG)) {
        try {
            s.close();
            return;
        } catch (IOException ex) {
            Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    ChatEventBus.getInstance().publishChat(msg);
    System.out.println("Chat Message placed on HZ Topic " + CHAT_TOPIC_NAME);

}
项目:JYLAND    文件:BroadSocket.java   
@OnMessage
public void onMessage(String message, Session session) throws IOException {
    logger.info("Welcome BroadSocket onMessage " + new Date());
    logger.info("Welcome BroadSocket onMessage " + message);
    synchronized(clients) {
        for(Session client : clients) {
            if(!client.equals(session)) {
                String msg=cf.rmScript(message);
                logger.info("Welcome BroadSocket onMessage " + msg);
                client.getBasicRemote().sendText(msg);
            }
        }
    }
}
项目:cjs_ssms    文件:WebSocketController.java   
/**
 * 收到客户端消息后调用的方法
 *
 * @param message 客户端发送过来的消息
 * @param session 可选的参数
 */
@OnMessage
public void onMessage(String message, Session session) {
  log.debug("来自客户端的消息:" + message);
  /*群发消息*/
  for (WebSocketController item : webSocketSet) {
    try {
      Principal principal = session.getUserPrincipal();
      if (null == principal) {
        log.debug("群发消息,未获取到当前用户认证信息。");
        continue;
      }
      item.serializeMessage(message,principal);
    } catch (IOException e) {
      e.printStackTrace();
      continue;
    }
  }
}
项目:ccow    文件:SubscriptionEndpoint.java   
@OnMessage
public void onWebSocketText(final Session sess, final JSONRPC2Message msg, @PathParam(CCOWContextListener.PATH_NAME) final String applicationName) {
    if (msg instanceof JSONRPC2Request) {
        //All operations that are invokable on ContextManager that does not return void
        logger.debug("The message is a Request");
    }
    else if (msg instanceof JSONRPC2Notification) {
        //All operations that are invokable on ContextManager that does return void
        logger.debug("The message is a Notification");
    }
    else if (msg instanceof JSONRPC2Response) {
        //All operations that are invokable from ContextManager that does not return void and are initially called from ContextManager
        participant.onMessage((JSONRPC2Response) msg);
        logger.debug("The message is a Response");
    }
}
项目:ccow    文件:WSClientConnection.java   
@OnMessage
public void onWebSocketText(final Session sess, final JSONRPC2Message msg) throws IOException, EncodeException {

    this.latestMessage = msg;

    if (msg instanceof JSONRPC2Request) {
        //All operations that are invokable on ContextManager that does not return void
        System.out.println("The message is a Request " + msg.toJSONString());
        final JSONRPC2Response data = new JSONRPC2Response(((JSONRPC2Request) msg).getID());
        final Map<String,String> result = Maps.newHashMap();
        result.put("decision", "valid");
        result.put("reason", "");
        data.setResult(result);
        sess.getBasicRemote().sendObject(data);
    }
    else if (msg instanceof JSONRPC2Notification) {
        //All operations that are invokable on ContextManager that does return void
        System.out.println("The message is a Notification " + msg.toJSONString());
    }
    else if (msg instanceof JSONRPC2Response) {
        //Can only be ContextChangesPending
        System.out.println("The message is a Response " + msg.toJSONString());
    }
}
项目:mycore    文件:MCRWebCLIResourceSockets.java   
@OnMessage
public void message(Session session, JsonObject request) {
    sessionized(session, () -> {
        LOGGER.info("Message ThreadID: {}", Thread.currentThread().getName());
        LOGGER.info("MyCore Session ID (message): {}", MCRSessionMgr.getCurrentSessionID());
        if (!MCRAccessManager.checkPermission("use-webcli")) {
            try {
                session.getBasicRemote().sendText("noPermission");
            } catch (IOException ex) {
                LOGGER.error("Cannot send message to client.", ex);
            }
            return;
        }
        handleMessage(session, request);
    });
}
项目:atmosphere-agent    文件:AgentEndpoint.java   
@OnMessage
public void onJsonMessage(String jsonMessage, Session session) {
    MessageAction messageAction = jsonUtil.getProperty(jsonMessage, JsonConst.MESSAGE_ACTION, MessageAction.class);

    switch (messageAction) {
        case ROUTING_ACTION:
            RequestMessage request = jsonUtil.deserializeRequest(jsonMessage);
            dispatcher.executeRoutingActionRequest(request);
            break;
        case ERROR:
            ResponseMessage response = jsonUtil.deserializeResponse(jsonMessage);
            LOGGER.error("Server error", response.getException());
            break;
        default:
            LOGGER.error("Invalid message action.");
            break;
    }
}
项目:javabase    文件:WeiXinLoginEndPoint.java   
@OnMessage
public void handleMessage(Session session, String message) {
    this.redisTemplate= SpringContextHolder.getBean("stringRedisTemplate");
    log.info("input param message="+message);
    //定义token 2分钟失效 失效退出循环
    redisTemplate.opsForValue().set(message,LoginStatus.invalid.toString(),2, TimeUnit.MINUTES);
    try {
        while(true){
            String code = redisTemplate.opsForValue().get(message);
            if(StringUtils.isNotEmpty(code)) {
                if (LoginStatus.login.toString().equals(code)){
                    session.getBasicRemote().sendText(new Result("0000","登录成功!",message).toJSONString());
                    break;
                }
            }else{
                session.getBasicRemote().sendText(new Result("4444","网页token失效!").toJSONString());
                break;
            }
            Thread.sleep(500);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:watchoverme-server    文件:EventEndpoint.java   
@OnMessage
public void requestEventTracking(@PathParam("trackingPin") String trackingPin, String message, Session session) {
    myLog.debug("requestEventTracking: " + trackingPin);
    try {
        if (session.isOpen()) {
            SecqMeEventVO eventVO = eventManager.getEventByTrackingPin(trackingPin);
            FullEventInfoVO eventInfoVO = eventManager.getFullEventInfoOfContact(eventVO.getId());
            session.getBasicRemote().sendText(eventInfoVO.toJSON().toString());
        }
    } catch (IOException ex) {
        myLog.error("Tracking event web socket error: " + trackingPin, ex);
        try {
            session.close();
        } catch (IOException ex1) {
            // Ignore
        }
    }
}
项目:sample.microprofile.meetingapp    文件:MeetingNotifier.java   
@OnMessage
public void onMessage(String id, Session s) throws IOException {
    JsonObject m = manager.get(id);
    if (m == null) {
        s.close();
        return;
    }

    JsonString url = m.getJsonString("meetingURL");

    if (url != null) {
        s.getBasicRemote().sendText(url.getString());
        s.close();
        return;
    }

    Queue<Session> sessions = listeners.get(id);
    if (sessions == null) {
        sessions = new ArrayBlockingQueue<>(1000);
        Queue<Session> actual = listeners.putIfAbsent(id, sessions);
        if (actual != null) {
            sessions = actual;
        }
    }
    sessions.add(s);
}
项目:OpenChatAlytics    文件:EventsResource.java   
/**
 * Called whenever a new event is received from the compute socket
 *
 * @param event
 *            The triggering event
 */
@OnMessage
public void onMessage(ChatAlyticsEvent event) {

    LOG.debug("Got realtime event: {}", event);

    // don't expose package info to client
    event.setClazz(null);

    Set<Session> closedSessions = Sets.newHashSet();
    for (Session clientSession : sessions) {
        if (!clientSession.isOpen()) {
            closedSessions.add(clientSession);
            continue;
        }

        clientSession.getAsyncRemote().sendObject(event);
    }

    sessions.removeAll(closedSessions);
}
项目:tomcat-8-wffweb-demo-apps    文件:WSServerForIndexPage.java   
/**
 * When a user sends a message to the server, this method will intercept the
 * message and allow us to react to it. For now the message is read as a
 * String.
 */
@OnMessage
public void onMessage(byte[] message, Session session) {

    browserPage.webSocketMessaged(message);

    if (message.length == 0) {
        LOGGER.info("client ping message.length == 0");
        if (httpSession != null
                && HTTP_SESSION_HEARTBEAT_INVTERVAL < (System
                        .currentTimeMillis() - lastHeartbeatTime)) {
            LOGGER.info("going to start httpsession hearbeat");
            HeartBeatUtil.ping(httpSession.getId());
            lastHeartbeatTime = System.currentTimeMillis();
        }
    }
}
项目:atmosphere-server    文件:ServerAgentEndpoint.java   
@OnMessage
public void onJsonMessage(String jsonMessage, Session session) {
    MessageAction messageAction = jsonUtil.getProperty(jsonMessage, JsonConst.MESSAGE_ACTION, MessageAction.class);

    switch (messageAction) {
        case REGISTER_AGENT:
            RequestMessage reqisterRequest = jsonUtil.deserializeRequest(jsonMessage);
            dispatcher.registerAgent(reqisterRequest, session);
            break;
        case DEVICE_CHANGED:
            RequestMessage deviceChangedRequest = jsonUtil.deserializeRequest(jsonMessage);
            dispatcher.deviceListChanged(deviceChangedRequest);
            break;
        case ROUTING_ACTION:
        case ERROR:
            dispatcher.sendToClient(jsonMessage);
            break;
        default:
            LOGGER.error(String.format("Unknown message action on the %s: %s",
                                       this.getClass().getSimpleName(),
                                       messageAction));
            break;
    }
}
项目:real1ty    文件:Application.java   
@OnMessage
public void receiveMessage(String message, Session session) throws IOException {
    String[] contents = splitRouting(message);

    // Who doesn't love switch on strings in Java 8?
    switch(contents[0]) {
        case "roomHello":
            sessions.add(session);
            addNewPlayer(session, contents[2]);
            break;
        case "room":
            processCommand(session, contents[2]);
            break;
        case "roomGoodbye":
            removePlayer(session, contents[2]);
            break;
    }
}
项目:iote2e    文件:ServerSideSocketBdbb.java   
/**
 * On web socket byte.
 *
 * @param bytes the bytes
 */
@OnMessage
public void onWebSocketByte(byte[] bytes) {
    logger.debug("onWebSocketByte len=" + bytes.length);
    if (authenticated) {
        try {
            while (true) {
                logger.debug("bytes len: " + bytes.length );
                ThreadEntryPointBdbb.fromClientByteArrays.add(ByteBuffer.wrap(bytes));
                break;
            }
        } catch (Exception e) {
            logger.error("Exception decoding Iote2eRequest: {}", e.getMessage(), e);
        }

    } else {
        logger.info("Invalid byte message, not logged in - need to force close the socket");
        // TODO: force close on socket
    }
}
项目:iote2e    文件:ServerSideSocketOmh.java   
/**
 * On web socket byte.
 *
 * @param bytes the bytes
 */
@OnMessage
public void onWebSocketByte(byte[] bytes) {
    logger.debug("onWebSocketByte len=" + bytes.length);
    if (authenticated) {
        try {
            while (true) {
                logger.debug("bytes len: " + bytes.length );
                ThreadEntryPointOmh.fromClientByteArrays.add(ByteBuffer.wrap(bytes));
                break;
            }
        } catch (Exception e) {
            logger.error("Exception decoding Iote2eRequest: {}", e.getMessage(), e);
        }

    } else {
        logger.info("Invalid byte message, not logged in - need to force close the socket");
        // TODO: force close on socket
    }
}
项目:atmosphere-client    文件:ClientEndpoint.java   
@OnMessage
public void onJsonMessage(String message, Session session) {
    MessageAction messageAction = jsonUtil.getProperty(message, JsonConst.MESSAGE_ACTION, MessageAction.class);

    switch (messageAction) {
        case ROUTING_ACTION:
        case DEVICE_ALLOCATION_INFORMATION:
        case GET_ALL_AVAILABLE_DEVICES:
        case ERROR:
        case RELEASE_DEVICE:
            ResponseMessage response = jsonUtil.deserializeResponse(message);
            communicationManager.addResponse(response);
            break;
        default:
            LOGGER.error("Unknown message action on the ClientEndpoint: " + messageAction);
            break;
    }
}
项目:SensorPanel    文件:WebSockletRunner.java   
@OnMessage
public void onMessage(String value) {
  double temp = Double.parseDouble(value);
  System.out.format("Temperature from Random service: %.2f", temp);
  try {
    if (temp > 30) {
      yellowLed.setValue(false);
      blueLed.setValue(false);
      redLed.setValue(true);
    } else if (temp < 10) {
      yellowLed.setValue(false);
      blueLed.setValue(true);
      redLed.setValue(false);
    } else {
      yellowLed.setValue(true);
      blueLed.setValue(false);
      redLed.setValue(false);
    }
  } catch (IOException ex) {
    Logger.getLogger(WebSockletRunner.class.getName()).log(Level.SEVERE, null, ex);
  }
}
项目:chatty    文件:WebsocketClient.java   
@OnMessage
public synchronized void onMessage(String message, Session session) {
    System.out.println("RECEIVED: " + message);
    timeLastMessageReceived = System.currentTimeMillis();
    handler.handleReceived(message);
    receivedCount++;
    try {
        String[] split = message.split(" ", 3);
        int id = Integer.parseInt(split[0]);
        String command = split[1];
        String params = "";
        if (split.length == 3) {
            params = split[2];
        }
        handleCommand(id, command, params);
    } catch (ArrayIndexOutOfBoundsException | NumberFormatException ex) {
        LOGGER.warning("[FFZ-WS] Invalid message: "+message);
    }
}
项目:chatty    文件:WebsocketClient.java   
/**
 * Receive Pong response, take the time from the payload and calculate
 * latency.
 * 
 * @param message 
 */
@OnMessage
public synchronized void onPong(PongMessage message) {
    try {
        long timeSent = message.getApplicationData().getLong();
        long latency = System.currentTimeMillis() - timeSent;
        lastMeasuredLatency = latency;
        timeLatencyMeasured = System.currentTimeMillis();
        if (latency > 200) {
            LOGGER.info(String.format("[FFZ-WS] High Latency (%dms)",
                    System.currentTimeMillis() - timeSent));
        }
    } catch (Exception ex) {
        LOGGER.warning("[FFZ-WS] Invalid Pong message: "+ex);
    }
}
项目:hawkular-commons    文件:AbstractGatewayWebSocket.java   
/**
 * When a binary message is received from a WebSocket client, this method will lookup the {@link WsCommand} for the
 * given request class and execute it.
 *
 * @param binaryDataStream contains the JSON request and additional binary data
 * @param session the client session making the request
 */
@OnMessage
public void onBinaryMessage(InputStream binaryDataStream, Session session) {
    String requestClassName = "?";
    try {
        // parse the JSON and get its message POJO, including any additional binary data being streamed
        BasicMessageWithExtraData<BasicMessage> reqWithData = new ApiDeserializer().deserialize(binaryDataStream);
        BasicMessage request = reqWithData.getBasicMessage();
        requestClassName = request.getClass().getName();
        log.infoReceivedBinaryData(requestClassName, session.getId(), endpoint);

        handleRequest(session, reqWithData);

    } catch (Throwable t) {
        log.errorWsCommandExecutionFailure(requestClassName, session.getId(), endpoint, t);
        String errorMessage = "BusCommand failed [" + requestClassName + "]";
        sendErrorResponse(session, errorMessage, t);
    }
}
项目:hawkular-commons    文件:AbstractGatewayWebSocket.java   
/**
 * When a message is received from a WebSocket client, this method will lookup the {@link WsCommand} for the
 * given request class and execute it.
 *
 * @param nameAndJsonStr the name of the API request followed by "=" followed then by the request's JSON data
 * @param session the client session making the request
 */
@OnMessage
public void onMessage(String nameAndJsonStr, Session session) {
    String requestClassName = "?";
    try {
        // parse the JSON and get its message POJO
        BasicMessageWithExtraData<BasicMessage> request = new ApiDeserializer().deserialize(nameAndJsonStr);
        requestClassName = request.getBasicMessage().getClass().getName();
        log.infoReceivedWsMessage(requestClassName, session.getId(), endpoint);

        handleRequest(session, request);

    } catch (Throwable t) {
        log.errorWsCommandExecutionFailure(requestClassName, session.getId(), endpoint, t);
        String errorMessage = "Failed to process message [" + requestClassName + "]";
        sendErrorResponse(session, errorMessage, t);
    }
}
项目:sample.async.websockets    文件:EchoEncoderEndpoint.java   
/**
 * Called when a message is received. The WebSocket container will take 
 * data from the socket, and will transform it into the parameter EchoObject
 * using the {@link EchoDecoder}.
 * @param o Parameters converted into an EchoObject via the <code>EchoDecoder</code>
 * @param session The session associated with this message
 * @throws IOException
 * @throws EncodeException
 */
@OnMessage
public void receiveMessage(EchoObject o, Session session)
        throws IOException, EncodeException {
    // Called when a message is received. 
    // Single endpoint per connection by default --> @OnMessage methods are single threaded!
    // Endpoint/per-connection instances can see each other through sessions.

    if (o.stopRequest()) {
        session.close();
    } else {
        // Simple broadcast
        for (Session s : session.getOpenSessions()) {
            s.getBasicRemote().sendObject(o);
        }
    }
}
项目:sample.async.websockets    文件:EchoEndpoint.java   
@OnMessage
public void receiveMessage(String message, Session session)
        throws IOException {
    // Called when a message is received. 
    // Single endpoint per connection by default --> @OnMessage methods are single threaded!
    // Endpoint/per-connection instances can see each other through sessions.

    if ("stop".equals(message)) {
        Hello.log(this, "Endpoint " + endptId + " was asked to stop");
        session.close();
    } else if (message.startsWith(AnnotatedClientEndpoint.NEW_CLIENT)) {
        AnnotatedClientEndpoint.connect(message);
    } else {
        final int id = count++;
        broadcast(session, id, message); // in EchoCommon
    }
}
项目:sample.async.websockets    文件:AnnotatedClientEndpoint.java   
@OnMessage
public void receiveMessage(String message, Session session) throws IOException {
    // Called when a message is received. 
    // Single endpoint per connection by default --> @OnMessage methods are single threaded!
    // Endpoint/per-connection instances can see each other through sessions.

    if ("stop".equals(message)) {
        Hello.log(this, "Client "+ id +" stopped, " + this);
        session.close();
    } else if (message.contains("client ") && message.contains("forwarded")) {
        String newMessage = message.replace("(forwarded)", ""); // strip the forwarded bit off.
        newMessage = newMessage.replace("(delayed)", ""); // strip the delayed bit off.
        int pos = newMessage.indexOf("client "); // strip the client bit off
        newMessage = newMessage.substring(pos + 7).trim();

        // Finalize the message with the client and message id
        newMessage = String.format(CLIENT_ECHO, id, count++, newMessage);

        Hello.log(this, "Client "+ id +" received '" + message + "' and will forward as '" + newMessage + "'");
        session.getBasicRemote().sendText(newMessage);
    } else {
        Hello.log(this, "Client "+ id +" received: " + message);
    }
}
项目:edit-2015    文件:BrickConnection.java   
/**
 * When a user sends a message to the server, this method will intercept the
 * message and allow us to react to it. For now the message is read as a
 * String.
 */
@OnMessage
public void onMessage(String message, Session session) {
    System.out.println("Message from " + session.getId() + ": " + message);
    try {
        final JsonObject jsonCommand = Json.createReader(new StringReader(message)).readObject();
        if (jsonCommand.getString("command").equals("end")) {
            AC.sendCommand(jsonCommand.toString());
            try {
                items.RemoveItem(currentId);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            AC.sendCommand(jsonCommand.toString());
        }

    } catch (Exception ex) {

        ex.printStackTrace();
    }
}
项目:edit-2015    文件:BrickCommandsEndpoint.java   
@OnMessage
public void execute(String json) {

    JsonArray jsonValues = Json.createReader(new StringReader(json))
            .readArray();

    List<JsonObject> jsonObjects = jsonValues.getValuesAs(JsonObject.class);
    jsonObjects.stream().forEach(
            jsonObject -> {
                jsonObject.getString("id");

                CommandWrapper command = new CommandWrapper(
                        "MoveToLocation", "X,Y");

                JsonObject jsonCommand = Json.createObjectBuilder()
                        .add("command", command.getCommand())
                        .add("data", command.getData()).build();

                try {
                    brickEndpoint.sendCommand(jsonCommand.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
}
项目:internet_of_things_simulator    文件:MyEventServerSocket.java   
@OnMessage
public void onWebSocketText(String message)
{
    System.out.println("Received TEXT message: " + message);
    try {
        if ((session != null) && (session.isOpen()))
        {
            System.out.println("Echoing back text message "+message);
            session.getAsyncRemote().sendText("Received: "+message,new SendHandler(){

    @Override
    public void onResult(SendResult arg0) {
        if (!arg0.isOK()){
            System.out.println("Error Sending Response: "+arg0.getException().getMessage());
        }
    }

            });
        }
    } catch (Exception e){
        System.out.println("Error: "+e.getMessage());
        e.printStackTrace();
    }
}
项目:msf4j    文件:EndpointDispatcher.java   
/**
 * Extract OnMessage method for String from the endpoint if exists.
 *
 * @param webSocketEndpoint Endpoint to extract method.
 * @return method optional to handle String messages.
 */
public Optional<Method> getOnStringMessageMethod(Object webSocketEndpoint) {
    Method[] methods = webSocketEndpoint.getClass().getMethods();
    Method returnMethod = null;
    for (Method method : methods) {
        if (method.isAnnotationPresent(OnMessage.class)) {
            Parameter[] parameters = method.getParameters();
            for (Parameter parameter: parameters) {
                if (!parameter.isAnnotationPresent(PathParam.class) &&
                        parameter.getType() == String.class) {
                    returnMethod = method;
                }

            }
        }
    }
    return Optional.ofNullable(returnMethod);
}
项目:msf4j    文件:EndpointDispatcher.java   
/**
 * Extract OnMessage method for Binary from the endpoint if exists.
 *
 * @param webSocketEndpoint Endpoint to extract method.
 * @return method optional to handle binary messages.
 */
public Optional<Method> getOnBinaryMessageMethod(Object webSocketEndpoint) {
    Method[] methods = webSocketEndpoint.getClass().getMethods();
    Method returnMethod = null;
    for (Method method : methods) {
        if (method.isAnnotationPresent(OnMessage.class)) {
            //Adding OnMessage according to their types
            Class<?>[] paraTypes = method.getParameterTypes();
            List<Class<?>> paraList = Arrays.asList(paraTypes);
            if (paraList.contains(byte[].class) || paraList.contains(ByteBuffer.class)) {
                returnMethod = method;
            }
        }
    }
    return Optional.ofNullable(returnMethod);
}
项目:StreamSis    文件:OBSStudioClient.java   
@OnMessage
public void onMessage(JsonObject json) {
    if (json.getString("update-type", null) != null) {
        logger.debug("Received 'update-type' message. Doing nothing.");
        return;
    }
    // If it's not "update-type" event, but a response, lets process it.
    String errorMessage = getErrorFromRawResponse(json);
    String id = json.getString("message-id", null);
    if (id != null) {
        NetUtil.startInNewThread(() -> {
            logger.debug("Received response with ID: " + id);
            RequestCallback callback = requestCallbacks.remove(id);
            if (callback != null)
                callback.processResponse(json, errorMessage);
            else
                logger.error(
                        "Callback with such ID is unknown: " + id + ". Doing nothing. o_O");
        });
    } else {
        logger.error("Wrong response received, it doesn't have 'message-id' field.");
    }
}
项目:gameboot    文件:WebSocketEndpoint.java   
/**
 * On message.
 *
 * @param msg
 *          the msg
 * @param session
 *          the session
 * @throws Exception
 *           the exception
 */
@OnMessage
public void onMessage(byte[] msg, Session session) throws Exception {
  log.debug("Message received for channel {}", session.getId());
  try {
    if (isEncrypting(session)) {
      try {
        decrypt(msg);
        return;
      } catch (Exception e) {
        log.error("Cannot decrypt: assuming delete request sent: {}", e.getMessage());
      }
    }

    unencrypted(session, msg);
  } finally {
    if (responseLatch != null) responseLatch.countDown();
  }
}
项目:diqube    文件:WebSocketEndpoint.java   
@OnMessage
public void onMessage(String msg, Session session) throws Exception {
  try {
    logger.trace("Received message on session {}: {}", session, msg);

    for (WebSocketEndpointListener listener : getBeanCtx(session).getBeansOfType(WebSocketEndpointListener.class)
        .values()) {
      listener.socketMessage();
    }

    JsonRequestDeserializer deserializer = getBeanCtx(session).getBean(JsonRequestDeserializer.class);
    JsonRequestRegistry requestRegistry = getBeanCtx(session).getBean(JsonRequestRegistry.class);
    JsonRequest request = deserializer.deserialize(msg, session);

    requestRegistry.registerRequest(session, request);

    request.executeCommand();
  } catch (Exception e) {
    logger.error("Exception on session {}. Swallowing.", session, e);
    // we must not re-throw the exception, otherwise the Websocket will be closed - we though do not want to do this
    // if just any command threw an exception.
  }
}
项目:firefly    文件:WebsocketConnector.java   
@OnMessage
public void onMessage(String message) {
    try {

        if (StringUtils.isEmpty(message)) return;  // ignore empty messages

        ServerEvent event = ServerEventQueue.parseJsonEvent(message);
        event.setFrom(session.getId());
        if (event.getTarget().getScope() == ServerEvent.Scope.CHANNEL ) {
            event.getTarget().setChannel(channelID);
        } else {
            event.getTarget().setConnID(session.getId());
        }
        ServerEventManager.fireEvent(event);
    } catch (Exception e) {
        LOG.error(e, "Error while interpreting incoming json message:" + message);
    }
}