package com.baoshi.swms.net.build;

import com.baoshi.swms.bean.User;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

/**
 * websocket客户端
 *
 * @author Zhendong Zhou
 * @date   2021/12/9 15:24
 */
public class WebSocketClient {
    private final Request request;
    private final OkHttpClient client;
    private WebSocket webSocket;

    public WebSocketClient() {
        client = new OkHttpClient();
        request = new Request.Builder()
                .url("wss://device.baoshi56.com/ws/android/"+ User.getLocalUser().getId())
                .build();
    }

    public void start(WebSocketListener listener) {
        client.dispatcher().cancelAll();
        webSocket = client.newWebSocket(request, listener);
    }

    public void close() {
        if (webSocket != null) {
            webSocket.close(1000, null);
        }
        client.dispatcher().executorService().shutdown();
    }
}
