如何从Javax.websocket上的Websocket订阅者(客户端)读取json请求?

时间:2017-09-04 05:47:02

标签: websocket java-websocket

以下是我的Websocket订阅代码。

客户方:

var request = '{"sessionId": "_fjuhdf896786767", "username":"admin", "status":true}'
ws = new WebSocket(wsUri);
console.log("registered");
    ws.onopen = function() {
        console.log("connection opened!")
        ws.send(request);
    }

    ws.onmessage = function(msg) {
        console.log("received message:");
        window.getData(JSON.parse(msg.data));
    }

在服务器端,websocket的实现如下:

@ServerEndPoint(value="/status")
public class WebsocketServer {

    @OnOpen
    public void OpenMsg(Session session, EndpointConfig cnfg) {

        String retdata = "";
        try {
            if (session.isOpen()) {
                log.info("OpenMsg() payload req data from client"  + decoder);
                retdata = getCount(decoder);
                log.info("OpenMsg() retdata " + retdata);
                session.getBasicRemote().sendText(retdata.toString());
                try {
                  Thread.sleep(pollinterval);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            try {
                session.close();
                log.error("Exception occured while Opening WS Session");
                e.printStackTrace();
            } catch (IOException e1) {
                // Ignore
            }
        }

    }                   
}

我想知道如何从" ws.send(request);"中读取json请求字符串。在服务器端(javax.websocket)。   我看到了编码器和解码器,但在这种情况下,我只是将json请求作为字符串发送,如上所示未编码。   任何人都可以告诉我,如何在Javax.websocket中将json字符串作为有效负载读取。

3 个答案:

答案 0 :(得分:0)

我想一个简单的JSON阅读器可以解决这个问题:

@OnMessage
public void onMessage(Session session, String message) {
    JsonObject json = Json.createReader(new StringReader(message)).readObject();
    System.out.println("Received json: " + json);
    // or do something more JSON-like:
    // String myField = json.getString("key");
}

编码器和解码器不直接链接到有效负载,而是希望直接操作对象。如果您使用解码器,则onMessage方法可能看起来像

@OnMessage
public void onMessage(Session session, MyMessageClass message){
    String myInput = message.getInput();
    String otherUsefulInformation = message.getInformation();
}

当您使用编码器时,它关于发送对象而不是纯文本:

@OnMessage
public void onMessage(Session session, MyMessageClass message){
    // process input

    MyAnswerClass answer = new MyAnswerClass(...);
    session.getBasicRemote().sendObject(answer);

    // without encoder, you are bound to use 
    // session.getBasicRemote().sendText(...)
    // or
    // session.getBasicRemote().sendBinary(...)
}

答案 1 :(得分:0)

Oracle Using WebSocket Protocal in WebLogic Server

Oracle OnMessage Interface

确保实现OnMessage接口

@OnMessage public void handleMessage(String message, Session session) { // message will contain the body content you sent }

答案 2 :(得分:0)

您可以在客户端使用批注“ ClientEndPoint”:

subgrid