Example of simple websocket connection from client

huangapple go评论68阅读模式
英文:

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()
}

huangapple
  • 本文由 发表于 2017年2月22日 00:51:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/42373320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定