使用Go的socket.io客户端

时间:2017-10-04 09:43:56

标签: go websocket socket.io

从工作socket.io示例(后端:Python / Flask,前端:socket.io.js v2.0.3)开始,我现在尝试使用Go设置客户端但是可以&#39 ; t甚至通过握手阶段。为长篇帖子道歉...(最后我还添加了一个Python客户端,它实现了我想在Go中实现的功能)

(以下工作):

后端

@socketio.on('connect', namespace='/endpoint')
def connect():
    print("Client connected with request sid "+request.sid)

@socketio.on('join', namespace='/endpoint')
def join(message):
    print("Server received from client:" +message)
    print("Client just joined room with request sid "+request.sid)
    join_room(request.sid)

前端

namespace = '/endpoint';
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace);

var client_join_message = "This is a client";    
socket.emit('join', client_join_message);

开发人员工具:我注意到一些请求,直到浏览器和服务器选择使用websockets和交换框架:

http://localhost:5000/socket.io/?EIO=3&transport=polling&t=LxcgetJ
http://localhost:5000/socket.io/?EIO=3&transport=polling&t=Lxcgetf&sid=025e105a5093467d994a891367380aa3
http://localhost:5000/socket.io/?EIO=3&transport=polling&t=Lxcgeti&sid=025e105a5093467d994a891367380aa3
ws://localhost:5000/socket.io/?EIO=3&transport=websocket&sid=025e105a5093467d994a891367380aa3
http://localhost:5000/socket.io/?EIO=3&transport=polling&t=Lxcgetw&sid=025e105a5093467d994a891367380aa3
http://localhost:5000/socket.io/?EIO=3&transport=polling&t=Lxcgetx&sid=025e105a5093467d994a891367380aa3

服务器日志:

"GET /socket.io/?EIO=3&transport=polling&t=LxcgetJ HTTP/1.1" 200 381 0.000322
Client connected with request sid 025e105a5093467d994a891367380aa3
"POST /socket.io/?EIO=3&transport=polling&t=Lxcgetf&sid=025e105a5093467d994a891367380aa3 HTTP/1.1" 200 219 0.000806
(6450) accepted ('127.0.0.1', 45034)
"GET /socket.io/?EIO=3&transport=polling&t=Lxcgeti&sid=025e105a5093467d994a891367380aa3 HTTP/1.1" 200 227 0.003941
"POST /socket.io/?EIO=3&transport=polling&t=Lxcgetw&sid=025e105a5093467d994a891367380aa3 HTTP/1.1" 200 219 0.001650
"GET /socket.io/?EIO=3&transport=polling&t=Lxcgetx&sid=025e105a5093467d994a891367380aa3 HTTP/1.1" 200 215 0.000235
Server received from client:This is a client
Client just joined room with request sid 025e105a5093467d994a891367380aa3


我尝试Go,(不起作用):

代码来自client中的github.com/graarh/golang-socketio示例:

package main

import (
    "github.com/graarh/golang-socketio"
    "github.com/graarh/golang-socketio/transport"
    "log"
    "runtime"
    "time"
)

func main() {

    runtime.GOMAXPROCS(runtime.NumCPU())

    c, err := gosocketio.Dial(
        gosocketio.GetUrl("127.0.0.1", 5000, false),
        transport.GetDefaultWebsocketTransport())
    if err != nil {
        log.Fatal(err)
    }

    err = c.On(gosocketio.OnDisconnection, func(h *gosocketio.Channel) {
        log.Fatal("Disconnected")
    })
    if err != nil {
        log.Fatal(err)
    }

    err = c.On(gosocketio.OnConnection, func(h *gosocketio.Channel) {
        log.Println("Connected")
    })
    if err != nil {
        log.Fatal(err)
    }

    time.Sleep(1 * time.Second)
}

转码输出:

Connected

服务器日志:

"GET /socket.io/?EIO=3&transport=websocket HTTP/1.1" 200 0 1.004291

我有什么遗失的吗?使用Go代码,我看不到任何sidtransport=polling ...此外,只有少数问题被[go] [socket.io]标记,这让我觉得我和我一样。我选择了错误的道路......我会对任何想法和想法感激不尽。

@John Weldon

您的代码产生以下内容:

客户端:

$ go run gotest5.go 
2017/10/11 11:21:40 Connected
2017/10/11 11:21:40 result ""
2017/10/11 11:21:40 Done

服务器:

(4380) wsgi starting up on http://127.0.0.1:5000
(4380) accepted ('127.0.0.1', 38860)
127.0.0.1 - - [11/Oct/2017 11:21:40] "GET /socket.io/?EIO=3&transport=websocket HTTP/1.1" 200 0 0.003100

请注意,服务器功能on.('connect'...)on.('join',...)没有生成日志。

Python客户端(它可以工作):

from socketIO_client import SocketIO, BaseNamespace

class ThisNamespace(BaseNamespace):
    def on_connect(self):
        print('[Connected]')
    def on_reconnect(self):
        print('[Reconnected]')
    def on_disconnect(self):
        print('[Disconnected]')

with SocketIO('127.0.0.1', 5000, ThisNamespace) as socketIO:
    this_namespace = socketIO.define(ThisNamespace, '/endpoint')

客户日志:

python3 test.py 
[Connected]
[Disconnected]
[Disconnected]

服务器日志:

(6047) wsgi starting up on http://127.0.0.1:5000
(6047) accepted ('127.0.0.1', 38900)
127.0.0.1 - - [11/Oct/2017 11:53:27] "GET /socket.io/?t=1507712007314-0&transport=polling&EIO=3 HTTP/1.1" 200 381 0.000859
(6047) accepted ('127.0.0.1', 38902)
Client connected with request sid 919ed69264dd4e9f93e7af0294970dbd
Client disconnected with request.sid 919ed69264dd4e9f93e7af0294970dbd
127.0.0.1 - - [11/Oct/2017 11:53:27] "GET /socket.io/?sid=919ed69264dd4e9f93e7af0294970dbd&transport=websocket&EIO=3 HTTP/1.1" 200 0 0.032171

2 个答案:

答案 0 :(得分:1)

我认为你做对了,除非你忘了实际发送join消息,可能是这样的:

package main

import (
        "log"
        "runtime"
        "sync"
        "time"

        "github.com/graarh/golang-socketio"
        "github.com/graarh/golang-socketio/transport"
)

func doSomethingWith(c *gosocketio.Client, wg *sync.WaitGroup) {
        if res, err := c.Ack("join", "This is a client", time.Second*3); err != nil {
                log.Printf("error: %v", err)
        } else {
                log.Printf("result %q", res)
        }
        wg.Done()
}

func main() {

        runtime.GOMAXPROCS(runtime.NumCPU())

        c, err := gosocketio.Dial(
                gosocketio.GetUrl("127.0.0.1", 3003, false),
                transport.GetDefaultWebsocketTransport())
        if err != nil {
                log.Fatal(err)
        }

        err = c.On(gosocketio.OnDisconnection, func(h *gosocketio.Channel) {
                log.Fatal("Disconnected")
        })
        if err != nil {
                log.Fatal(err)
        }

        err = c.On(gosocketio.OnConnection, func(h *gosocketio.Channel) {
                log.Println("Connected")
        })
        if err != nil {
                log.Fatal(err)
        }

        wg := &sync.WaitGroup{}
        wg.Add(1)
        go doSomethingWith(c, wg)
        wg.Wait()
        log.Printf("Done")
}

注意goroutine调用实际将“join”消息传递给服务器的函数。

另外,请注意在goroutine完成之前使用sync.WaitGroup来阻止,而不是使用time.Sleep()等待。

答案 1 :(得分:1)

根据上述评论,我们发现websocket连接本身正在运行。问题就在这里 - socket.io是多年前开发的,当时大多数浏览器和中间服务器/代理/路由器都没有很好地支持本机WebSockets。因此,在升级和降级连接时(例如,对于longpolling),它有一个特殊的检查和后备。如果您已经安装了连接,则无需与其他协议进行特殊密钥交换即可开始工作。

尝试开始使用连接并在应用程序级别逻辑(Join等)上执行后续步骤。它有效吗?

我认为现在WS对99%的客户都有很好的支持。如果您不想失去一些客户将无法工作的机会,您可以在项目中保留sockets.io。但有时你必须在WS中实现它的连接逻辑。