微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么当Python socketio客户端连接到Go socketio服务器时未激活连接功能?

如何解决为什么当Python socketio客户端连接到Go socketio服务器时未激活连接功能?

我使用Python Socket.IO构建了一个socket.io客户端:

import socketio
import time

sio = socketio.Client(logger=True,engineio_logger=True)
is_connect = False

@sio.on("connect")
def connect():
    global is_connect
    print("is_connect value before connect:",is_connect)
    is_connect = True
    print(f"connection established with sid {sio.sid}")
    
def message_received(data):
    print(f'message was received!!!\n')
    print(f"message returned from server: {data}")

@sio.on("message")
def my_message(data):
    print("Messages from server: ",data)

@sio.on("disconnect")
def disconnect():
    global is_connect
    print("is_connect value before disconnet:",is_connect)
    is_connect = False
    print("disconnected from server")

sio.connect("http://localhost:9000") 
time.sleep(3)
sio.emit("chat message","Hello!",callback=message_received)
time.sleep(3)
sio.disconnect()

然后我使用an online example在Go中构建了一个socket.io服务器:

package main

//
// Command line arguments can be used to set the IP address that is listened to and the port.
//
// $ ./chat --port=8080 --host=127.0.0.1
//
// Bring up a pair of browsers and chat between them.
//

import (
    "flag"
    "fmt"
    "log"
    "net/http"
    "os"

    "github.com/mlsquires/socketio"
    "github.com/pschlump/MiscLib"
    "github.com/pschlump/godebug"
)

// Port is the port to listen to
var Port = flag.String("port","9000","Port to listen to") 
// HostIP is the host name or IP address to listen on
var HostIP = flag.String("host","localhost","Host name or IP address to listen on") 
// Dir is the directry where files are served from
var Dir = flag.String("dir","./asset","Direcotry where files are served from") 
func init() {
    flag.StringVar(Port,"P","Port to listen to")                           
    flag.StringVar(HostIP,"H","Host name or IP address to listen on") 
    flag.StringVar(Dir,"d","Direcotry where files are served from")     
}

func main() {

    flag.Parse()
    fns := flag.Args()

    if len(fns) != 0 {
        fmt.Printf("Usage: Invalid arguments supplied,%s\n",fns)
        os.Exit(1)
    }

    var hostIP string = ""
    if *HostIP != "localhost" {
        hostIP = *HostIP
    }

    // Make certain that the command line parameters are handled correctly
    // fmt.Printf("host_ip >%s< HostIP >%s< Port >%s<\n",host_ip,*HostIP,*Port)

    server,err := socketio.NewServer(nil)
    if err != nil {
        log.Fatal(err)
    }

    server.On("connection",func(so socketio.socket) {
        fmt.Printf("%sa user connected with id %s%s,MiscLib.ColorGreen,so.Id(),MiscLib.ColorReset,godebug.LF())
        so.Join("chat")
        so.On("chat message",func(msg string) string {
            fmt.Printf("%schat message,%s%s,msg,godebug.LF())
            so.broadcastTo("chat","message",msg)
            return msg
        })
        so.On("disconnect",func() {
            fmt.Printf("%suser disconnect%s,MiscLib.ColorYellow,godebug.LF())
        })
    })

    server.On("error",func(so socketio.socket,err error) {
        fmt.Printf("Error: %s,err,godebug.LF())
    })

    http.Handle("/socket.io/",server)
    http.Handle("/",http.FileServer(http.Dir(*Dir)))
    fmt.Printf("Serving on port %s,brows to http://localhost:%s/\n",*Port,*Port)
    listen := fmt.Sprintf("%s:%s",hostIP,*Port)
    log.Fatal(http.ListenAndServe(listen,nil))
}

当客户端尝试连接到服务器时,确实会发生连接。但是,未激活Python socket.io客户端中的connect函数。这是建立连接后的日志:

Attempting polling connection to http://localhost:9000/socket.io/?transport=polling&EIO=3
Polling connection accepted with {'sid': 'Kon2_JkRCg9o4B8F_8Ab','upgrades': ['websocket'],'pingInterval': 25000,'pingTimeout': 60000}
Engine.IO connection established
Attempting WebSocket upgrade to ws://localhost:9000/socket.io/?transport=websocket&EIO=3
WebSocket upgrade was successful
Sending packet PING data None
Received packet PONG data None
Received packet PING data None
Received unexpected packet of type 2
Sending packet PING data None
Received packet PONG data None

与此同时,“聊天消息”和“断开连接”事件运行良好,它们的功能都已激活,回调函数也起作用。

为什么在建立socket.io连接时未激活Python socket.io客户端中的connect函数?我想念什么吗?请给我一些反馈,谢谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。