如何使用大猩猩连接到网络袜子?

我希望看到一个最小而简单的例子,说明如何使用大猩猩连接到websocket。

我发现连接到websocket的唯一例子是这个,但我无法理解它,我找不到它是如何工作的解释。

编辑:

第 20 行:
为什么他保留了 websocket 地址而不是变量字符串?flag.String

第26行:
这部分是否会产生一个信号,当用户按下crtl + C时通知程序?

interrupt: = make(chan os.Signal, 1)
signal.Notify (interrupt, os.Interrupt)

第32行:
这条线有什么作用?

websocket.DefaultDialer.Dial (u.String (), nil)

第60行:
因为不是?[]byte(t.String())t.string()


呼如林
浏览 126回答 1
1回答

饮歌长啸

该示例说:README客户端每秒发送一条消息,并打印收到的所有消息。查看代码,后一部分(打印收到的所有消息)发生在这里:go func() {&nbsp; &nbsp; defer close(done)&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; _, message, err := c.ReadMessage()&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Println("read:", err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; log.Printf("recv: %s", message)&nbsp; &nbsp; }}()这将启动一个 goroutine,该 goroutine 在循环中读取来自(websocket 连接)的消息并将其打印出来。当读取失败时,它会停止,这会发生错误和连接关闭。c主 goroutine 是这样做的:ticker := time.NewTicker(time.Second)defer ticker.Stop()for {&nbsp; &nbsp; select {&nbsp; &nbsp; case <-done:&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; case t := <-ticker.C:&nbsp; &nbsp; &nbsp; &nbsp; err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Println("write:", err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; case <-interrupt:&nbsp; &nbsp; &nbsp; &nbsp; log.Println("interrupt")&nbsp; &nbsp; &nbsp; &nbsp; // Cleanly close the connection by sending a close message and then&nbsp; &nbsp; &nbsp; &nbsp; // waiting (with timeout) for the server to close the connection.&nbsp; &nbsp; &nbsp; &nbsp; err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Println("write close:", err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case <-done:&nbsp; &nbsp; &nbsp; &nbsp; case <-time.After(time.Second):&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }}它有一个每秒触发的股票代码,在该服务器上,一条消息被发送到websocket。当读取器完成时,它关闭通道,该通道也发出此循环的信号,并退出。doneselect最后,有一个“中断”选择来处理Ctrl+C,干净利落地停止客户端。要回答您的具体问题:第 20 行:此标志使您能够在执行程序时从命令行设置地址,而不是对其进行硬编码。例如,您可以称它为设置其他端口。另请参见 https://gobyexample.com/command-line-flagsclient -addr localhost:9044第26行:是的,这是为了;另请参见 https://gobyexample.com/signalsCtrl+C第 32 行:是程序包中预配置的拨号程序。根据文档,它相当于DefaultDialerwebsocketvar DefaultDialer = &Dialer{&nbsp; &nbsp; Proxy:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; http.ProxyFromEnvironment,&nbsp; &nbsp; HandshakeTimeout: 45 * time.Second,}第 60 行:WriteMessage 采用 一个 ,因此您必须将字符串转换为[]byte[]byte
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go