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

时间:2020-10-09 19:02:16

标签: go socket.io python-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", "9000", "Port to listen to")                           
    flag.StringVar(HostIP, "H", "localhost", "Host name or IP address to listen on") 
    flag.StringVar(Dir, "d", "./asset", "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, %s\n", 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, %s\n", MiscLib.ColorGreen, msg, MiscLib.ColorReset, godebug.LF())
            so.BroadcastTo("chat", "message", msg)
            return msg
        })
        so.On("disconnect", func() {
            fmt.Printf("%suser disconnect%s, %s\n", MiscLib.ColorYellow, MiscLib.ColorReset, godebug.LF())
        })
    })

    server.On("error", func(so socketio.Socket, err error) {
        fmt.Printf("Error: %s, %s\n", 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函数?我想念什么吗?请给我一些反馈,谢谢!

0 个答案:

没有答案