英文:
Example of simple websocket connection from client
问题
我想将这段在Node中运行的JavaScript代码改写成Go语言。
package main
import (
"fmt"
"log"
"github.com/googollee/go-socket.io"
)
func main() {
socket, err := socketio.Dial("http://botws.generals.io")
if err != nil {
log.Fatal(err)
}
socket.On("connect", func() {
fmt.Println("Connected to server.")
})
// 其他代码...
socket.Close()
}
请注意,这里使用了 go-socket.io
库来处理Socket.IO连接。你可以使用 go get
命令安装该库:
go get github.com/googollee/go-socket.io
希望对你有帮助!如果你有其他问题,请随时提问。
英文:
I would like to rewrite this JavaScript (run in Node) into Go.
let io = require('socket.io-client');
let socket = io('http://botws.generals.io');
socket.on('connect', function() {
console.log('Connected to server.');
});
(I've tried this library unsuccessfully; I can elaborate on my noob attempts if that helps)
答案1
得分: 2
好的,以下是翻译好的代码:
package main
import (
"github.com/graarh/golang-socketio"
"github.com/graarh/golang-socketio/transport"
"log"
)
func main() {
transport := transport.GetDefaultWebsocketTransport()
ws_url := "ws://botws.generals.io/socket.io/?EIO=3&transport=websocket"
client, err := gosocketio.Dial(ws_url, transport)
if err != nil {
log.Fatal(err)
}
client.On(gosocketio.OnConnection, func(c *gosocketio.Channel, args interface{}) {
log.Println("已连接!")
})
// 阻塞以给客户端连接的时间
select {}
client.Close()
}
请注意,我只翻译了代码部分,其他内容都被忽略了。
英文:
Ok, got it working. There was a different URL I had to use.
package main
import (
"github.com/graarh/golang-socketio"
"github.com/graarh/golang-socketio/transport"
"log"
)
func main() {
transport := transport.GetDefaultWebsocketTransport()
ws_url := "ws://botws.generals.io/socket.io/?EIO=3&transport=websocket"
client, err := gosocketio.Dial(ws_url, transport)
if err != nil {
log.Fatal(err)
}
client.On(gosocketio.OnConnection, func(c *gosocketio.Channel, args interface{}) {
log.Println("Connected!")
})
// Block to give client time to connect
select {}
client.Close()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论