SpringBoot integrates websocket (4) | (use okhttp3 to implement websocket)

SpringBoot integrates websocket (4) | (use okhttp3 to implement websocket)


Chapter
Chapter 1 link: SpringBoot integrates websocket (1) | (websocket client implementation)
Chapter 2 link: SpringBoot integrates websocket (2) | (websocket server implementation and websocket transfer implementation)

Preface

HTTP is a network method commonly used by modern applications to exchange data and media. Efficient use of HTTP can make resources load faster and save bandwidth. OkHttp is an efficient HTTP client with the following default features:

Support HTTP/2, allowing all requests with the same host address to share the same socket connection
Connection pool reduces request delay
Transparent GZIP Compression reduces the size of response data
Cache response content to avoid some completely duplicate requests
Automatically retry other IPs of the host and automatically redirect when the request fails a>
will fall back to TLS 1.0 when the handshake fails

1. Implementation steps

1. Implementation steps

1. Build OkHttpClient configuration and initialize some parameters.
2. Use the URL address of WebSocket to connect.
3. Set the connection status callback and message callback of WebSocket.
4. Parse message json processing business, etc.
5. After the connection is successful, use WebSocket to send messages

2. Websocket service code implementation

1.WebSocketListener implementation

springboot connects to WS interface

@Slf4j
public class SparkChatInnerServer extends WebSocketListener {
    
    

    public StringBuilder stringBuilder;
    public Boolean wsCloseFlag;

    // 构造函数
    public SparkChatInnerServer(Boolean wsCloseFlag) {
    
    
        this.wsCloseFlag = wsCloseFlag;
        this.stringBuilder = new StringBuilder();
    }

    /**
     * 开启连接
     *
     * @param webSocket
     * @param response
     */
    @Override
    public void onOpen(WebSocket webSocket, Response response) {
    
    
        super.onOpen(webSocket, response);
        log.info("内部 连接ws服务");
    }

    /**
     * 收到ws服务返回的数据
     *
     * @param webSocket
     * @param text
     */
    @Override
    public void onMessage(WebSocket webSocket, String text) {
    
    
        log.debug("收到的数据:{}", text);
        JsonParse myJsonParse = JSON.parseObject(text).toJavaObject(JsonParse.class);
        if (myJsonParse.header.code != 0) {
    
    
            log.error("发生错误,错误码为:{}", myJsonParse.header.code);
            log.error("本次请求的sid为:{}", myJsonParse.header.sid);
            wsCloseFlag = true;
            webSocket.close(1000, "");
        }
        List<Text> textList = myJsonParse.payload.choices.text;
        for (Text temp : textList) {
    
    
            stringBuilder.append(temp.content);
        }
        if (myJsonParse.header.status == 2 || myJsonParse.payload.choices.status == 2) {
    
    
            wsCloseFlag = true;
            webSocket.close(1000, "");
        }
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
    
    
        wsCloseFlag = true;
        super.onFailure(webSocket, t, response);
        try {
    
    
            if (null != response) {
    
    
                int code = response.code();
                log.error("会话异常:code:{},body:{}", code, response.body().string());
                if (101 != code) {
    
    
                    System.out.println("connection failed");
                }
            }
        } catch (IOException e) {
    
    
            log.error("会话异常:{}", e.getMessage());
        }
    }

}

2. Call implementation

springboot provides external websocket interface implementation


   public String sparkQueryBase(String sendparam, String chatUrl) throws Exception {
    
    
        String url = AuthUtils.assembleRequestUrl(chatUrl, websocketConfigConst.apiKey, websocketConfigConst.apiSecret, "GET");
        OkHttpClient client = new OkHttpClient.Builder().build();
        Request request = new Request.Builder().url(url).build();
        SparkChatInnerServer sparkChatInnerServer = new SparkChatInnerServer(false);
        WebSocket webSocket = client.newWebSocket(request, sparkChatInnerServer);
        webSocket.send(sendparam);
        // 获取返回结果
        int i = 0;
        while (true) {
    
    
            Thread.sleep(100);
            if (sparkChatInnerServer.wsCloseFlag) {
    
    
                break;
            }
            if (i > 120) {
    
    
                log.error("ws服务连接超时,无法进行问题收集");
                break;
            }
            i++;
        }
        webSocket.close(1000, "");
        return sparkChatInnerServer.stringBuilder.toString();
    }

Summarize

This article mainly introduces OkHttp3 to implement websocket client, and at the same time, it serves mobile websocket request parameters through request service.

Link to Chapter 1: SpringBoot integrates websocket (1)|(websocket client implementation)
Link to Chapter 2: SpringBoot integrates websocket (2) | (websocket server implementation and websocket transfer implementation)

Guess you like

Origin blog.csdn.net/Oaklkm/article/details/132667640