登录
首页 >  Golang >  Go问答

golang 中的 WebSocket

来源:stackoverflow

时间:2024-04-14 20:21:31 109浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《golang 中的 WebSocket》,聊聊,我们一起来看看吧!

问题内容

我正在尝试将 python websocket 客户端连接字符串转换为 golang。这是python代码

from websocket import create_connection

connection_string = "ws:// 10.1.2.3/socket{0}".format(token)

ws = create_connection(connection_string, sslopt={"check_hostname": false}) 

我在 golang 中创建了相同的内容,如下所示:

package main

import (
    "crypto/tls"
    "flag"
    "fmt"
    "github.com/gorilla/mux"
    "github.com/gorilla/websocket"
    log "github.com/sirupsen/logrus"
    "net/http"
    "os"
    "os/signal"
    "time"
)

func main() {
    router := mux.newrouter()
    router.handlefunc("/nexus", nexus).methods("post")
    log.fatal(http.listenandserve(":12345", router))
}

func nexus(writer http.responsewriter, request *http.request) {
    flag.parse()

    interrupt := make(chan os.signal, 1)
    signal.notify(interrupt, os.interrupt)

    token := "gkzl5nlrzjl5+jqchouaz9cyjge58w/pmccr+lexmdo0obg9nbiwo1vbo7+yc1oijl9ms6i9qh62bkx+xddhe0jyrtmsg4jckz4t3bcp2mxy3vbmgojjwz76zouf9v9ad6xl83lyor4blbzqbssu1r2niguotcgwjzt5jx6cjf0="

    socketurl := "wss://" + "10.1.2.3" + "/socket" + fmt.sprintf(token)

    log.println("connecting to nexus event channel...")
    config := tls.config{}
    dialer := websocket.dialer{
        tlsclientconfig: &config,
    }
    //check_hostname:=false
    //request.header.add("check_hostname","false")
    conn, _, err := dialer.dial(socketurl, nil)
    if err != nil {
        log.fatal("dial:", err)
    }
    defer conn.close()
    done := make(chan struct{})

    go func() {
        defer close(done)
        for {
            _, message, err := conn.readmessage()
            if err != nil {
                log.println("read:", err)
                return
            }
            log.printf("recv: %s", message)
        }
    }()

    ticker := time.newticker(time.second)
    defer ticker.stop()

    for {
        select {
        case <-done:
            return
        case t := <-ticker.c:
            err := conn.writemessage(websocket.textmessage, []byte(t.string()))
            if err != nil {
                log.println("write:", err)
                return
            }
        case <-interrupt:
            log.println("interrupt")

            // cleanly close the connection by sending a close message and then
            // waiting (with timeout) for the server to close the connection.
            err := conn.writemessage(websocket.closemessage, websocket.formatclosemessage(websocket.closenormalclosure, ""))
            if err != nil {
                log.println("write close:", err)
                return
            }
            select {
            case <-done:
            case <-time.after(time.second):
            }
            return
        }
    }
}

当我尝试从客户端调用它时,出现错误:

time="2021-10-07T12:45:22+05:30" level=info msg="Connecting to nexus event channel..."
time="2021-10-07T12:45:43+05:30" level=fatal msg="dial:dial tcp 10.1.2.3:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond."

Process finished with the exit code 1

根据我的理解,它失败是因为 url 字符串中的 sslopt 。任何 go 参考代码都将有助于解决该问题。


正确答案


  1. 确保目标端口为 443。
  2. socketurl 看起来与 connection_string = "ws:// 10.1.2.3/socket{0}".format(token)wssws 不同。

我尝试使用您的代码连接 server,如果我将 wss 更改为 ws,它就可以工作。

p1gd0g$ gor main.go
INFO[0000] Connecting to nexus event channel...         
INFO[0001] recv: 2021-10-08 21:13:36.7483105 +0800 CST m=+1.001602801 
INFO[0002] recv: 2021-10-08 21:13:37.748889 +0800 CST m=+2.002181301 
INFO[0003] recv: 2021-10-08 21:13:38.7482128 +0800 CST m=+3.001505101 
INFO[0004] recv: 2021-10-08 21:13:39.74902 +0800 CST m=+4.002312301 
INFO[0005] recv: 2021-10-08 21:13:40.74893 +0800 CST m=+5.002222501 
^CINFO[0005] interrupt                                    
INFO[0005] read: websocket: close 1000 (normal)

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《golang 中的 WebSocket》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>