package com.goafanti.common.bean;

import com.goafanti.common.utils.LoggerUtils;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

public class WebSocketClientBean {

    private static String url="ws://chat.xunmengren.net:11000/ws/1683470612048";
    private static String test_url="ws://localhost:8888/websocket/10086";
//    @Bean
    public static WebSocketClient webSocketClient() {
        try {
            WebSocketClient webSocketClient = new WebSocketClient(new URI(test_url),new Draft_6455()){

                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    LoggerUtils.debug(getClass(),"建立连接");
                }

                @Override
                public void onMessage(String s) {
                    LoggerUtils.debug(getClass(),"收到来自服务端消息："+s);
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    LoggerUtils.debug(getClass(),"关闭连接:::" + "i = " + i + ":::s = " + s +":::b = " + b);
                }

                @Override
                public void onError(Exception e) {
                    LoggerUtils.debug(getClass(),"报错了:::" + e.getMessage());
                }

                @Override
                public void send(String text) {
                    LoggerUtils.debug(getClass(),"发送消息：：："+text);
                    super.send(text);
                }
            };

            webSocketClient.connect();
            return webSocketClient;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {
        WebSocketClient webSocketClient = webSocketClient();
        //先等待连接上
        while (!webSocketClient.getReadyState().equals(ReadyState.OPEN)){

        }
        webSocketClient.send("666");
        webSocketClient.close();
    }
}
