获取OnMessage() websocket的值



我在客户端使用websocket (javascript),在服务器端使用java类。

这是我的WordgameServerEndpoint侧类

@ServerEndpoint(value = "/socket")
public class WordgameServerEndpoint {
private Logger logger = Logger.getLogger(this.getClass().getName());
@OnOpen
public void onOpen(Session session) {
    logger.info("Connected ... " + session.getId());
}
@OnMessage
public String onMessage(String unscrambledWord, Session session) {
        logger.info("Starting the game by sending first word");
    return unscrambledWord;
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
    logger.info(String.format("Session %s closed because of %s", session.getId(), closeReason));
}
}

这是WebSocketServer类

public class WebSocketServer {
public static void main(String[] args) {
    runServer();
}
public static void runServer() {
    Server server = new Server("localhost", 9988, "/websockets", WordgameServerEndpoint.class);
    try {
        server.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Please press a key to stop the server.");
        //reader.readLine();
        System.out.println(reader.readLine());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        server.stop();
    }
}
}

这是我的javascript函数用来发送消息

   $scope.savedata=function(){
             socket= new WebSocket('ws://majed-PC:9988/websockets/socket');
              socket.onopen= function() {
                 socket.send('hello');
              };
  };

如何在服务器端获得发送消息的值?

参见

@OnMessage
public String onMessage(String unscrambledWord, Session session) {
    logger.info("Starting the game by sending first word");
    return unscrambledWord;
}

在服务器端。unscrambledWord为接收到的消息。您的实现只是回送它,这可能不是您想要做的-只需将您的逻辑放在那里。

相关内容

  • 没有找到相关文章

最新更新