我在客户端(javascript)使用websocket,在服务器端使用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');
};
};
如何在服务器端获取已发送消息的值?
答案 0 :(得分:1)
见
@OnMessage
public String onMessage(String unscrambledWord, Session session) {
logger.info("Starting the game by sending first word");
return unscrambledWord;
}
在服务器端。 unscrambledWord
是收到的消息。你的实现只是回应它,这可能不是你想要做的 - 只需将你的逻辑放在那里。