报错日志

问题分析:在发送消息时提示没有连接异常,附业务代码

WebSocketChatClientUtil chatclient = new WebSocketChatClientUtil(url);
// websocket消息体
try {
    chatclient.connectBlocking();
    chatclient.send(JSONObject.toJSONString(msg, SerializerFeature.WriteMapNullValue));
} finally {
    if (!chatclient.isClosed()) {
        chatclient.closeBlocking();
    }
}

源码分析

// WebSocketImpl.java send()方法 
private void send(Collection<Framedata> frames) {
    if (!this.isOpen()) {
        throw new WebsocketNotConnectedException();
    } else if (frames == null) {
        throw new IllegalArgumentException();
    } else {
        ArrayList<ByteBuffer> outgoingFrames = new ArrayList();
        Iterator var3 = frames.iterator();

        while(var3.hasNext()) {
            Framedata f = (Framedata)var3.next();
            log.trace("send frame: {}", f);
            outgoingFrames.add(this.draft.createBinaryFrame(f));
        }

        this.write((List)outgoingFrames);
    }
}

// WebSocketClient.java send()方法 要求this.engine.isOpen()是false
public void send(String text) {
    this.engine.send(text);
}

//创建连接时,connect()方法通过创建一个新的线程来开启连接
public boolean connectBlocking() throws InterruptedException {
    this.connect();
    this.connectLatch.await();
    return this.engine.isOpen();
}
public void connect() {
    if (this.connectReadThread != null) {
        throw new IllegalStateException("WebSocketClient objects are not reuseable");
    } else {
        this.connectReadThread = new Thread(this);
        this.connectReadThread.setName("WebSocketConnectReadThread-" + this.connectReadThread.getId());
        this.connectReadThread.start(); //运行run方法,开启连接,详细代码省略
    }
}

处理方法:发送消息前,判断连接是否是打开状态

try {
    chatclient.connectBlocking();
    while(!(ReadyState.OPEN).equals(chatclient.getReadyState())){
        logger.info("socket连接还未打开");
    }
    chatclient.send(JSONObject.toJSONString(msg, SerializerFeature.WriteMapNullValue));
} finally {
    if (!chatclient.isClosed()) {
        chatclient.closeBlocking();
    }
}
Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐