java的连接wss的websocket服务器代码如何转成go代码

有段代码是访问websocket服务器,用wss,但是客户端又不需要证书,所以要设置证书验证false。这种参数化的访问websocket服务器,如何转化成go的代码呢?

final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();
ClientManager client = ClientManager.createClient();
SslEngineConfigurator sslEngineConfigurator = new SslEngineConfigurator(trustAllHttpsCertificates());
sslEngineConfigurator.setHostVerificationEnabled(false);
sslEngineConfigurator.setClientMode(true);
sslEngineConfigurator.setWantClientAuth(false);
sslEngineConfigurator.setNeedClientAuth(false);
client.getProperties().put(ClientProperties.SSL_ENGINE_CONFIGURATOR, sslEngineConfigurator);
client.connectToServer(new Endpoint() {
    @Override
    public void onOpen(Session session, EndpointConfig config) {
        try {
            se = session;
            se.addMessageHandler(new MessageHandler.Whole<byte[]>() {
                @Override
                public void onMessage(byte[] data) {
                    try {
                        accept_response(data);
                    } catch (InvalidProtocolBufferException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}, cec, new URI("wss://180.153.125.120:8088"));

共 1 个回复


xjjrocker

自己解决了,主要是网上找来找去都没有go作为websocket的client去连接wss服务器的,这里给出解决方案,以供后来人借鉴。

import (
    "crypto/tls"
    "github.com/gorilla/websocket"
)

func main() {
url := "wss://xxx.xxx.xxx.xxx:8088"
config := tls.Config{InsecureSkipVerify: true}
websocket.DefaultDialer.TLSClientConfig = &config
conn, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
    fmt.Printf("err=" + err.Error())
}
defer conn.Close()
fmt.Println("connect ", url, " success")
}
# 0