java 实现WebSocketClient客户端

java | 2020-07-10 17:21:36

java 实现WebSocketClient客户端案例,向websocket服务端发送消息监听消息,并实现发送马上接受返回值即时调用的方式

1.java 代码

public class MyWebSocket extends WebSocketClient {
    private int code;
    private String message;
    private boolean isPagefinished;
    public MyWebSocket(URI serverUri) {
        super(serverUri);
        this.waitConnect();

    }
    public void waitConnect(){
        try {
            this.connectBlocking();
        } catch (InterruptedException e) {
            log.error(e.getMessage(),e);
        }
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        log.warn("###建立连接");
    }

    @Override
    public void onMessage(String s) {
        //log.warn("接受消息:"+s);
        synchronized(this) {
            if (!StringUtils.isEmpty(s)) {
                JSONObject obj = JSON.parseObject(s);
                if (obj.containsKey("id") && obj.getIntValue("id") == code) {
                    //处理交互消息
                    this.message = s;
                    this.notify();
                    if(obj.getIntValue("id")!=900)log.warn("接受内容消息:"+s);
                }else if(obj.containsKey("method") && "Page.lifecycleEvent".equals(obj.getString("method"))){
                    //处理事件消息
                    JSONObject eventObj=obj.getJSONObject("params");
                    //渲染完成事件
                    if(eventObj.containsKey("name")&&("firstMeaningfulPaint".equals(eventObj.getString("name"))||"networkIdle".equals(eventObj.getString("name")))){
                        this.setPagefinished(true);
                    }
                    log.warn("接受事件消息:"+s);
                }
            }
        }

    }

    @Override
    public void onClose(int i, String s, boolean b) {
        log.warn("###关闭连接:"+this.getURI()+"-"+i+"-"+s+"-"+b);
    }

    @Override
    public void onError(Exception e) {
        log.error("###通信错误"+e.getMessage(),e);
    }

    public String sendAndGet(String text,int code) {
        synchronized(this) {
            message = null;
            this.code = code;
            try {

                this.send(text);
                this.wait(120000);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        }
        return message;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public boolean isPagefinished() {
        return isPagefinished;
    }

    public void setPagefinished(boolean pagefinished) {
        isPagefinished = pagefinished;
    }
}

 

2.websocket依赖

    <dependency>
      <groupId>org.java-websocket</groupId>
      <artifactId>Java-WebSocket</artifactId>
      <version>1.4.0</version>
    </dependency>

 

登录后即可回复 登录 | 注册
    
关注编程学问公众号