Why the connection function is not activated when Python socketio client connects to Go socketio server?

1.2k views Asked by At

I built a socket.io client by using Python 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()

And then I built a socket.io server in Go by using an online example:

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

When the client tries to connect to the server, the connection does happen. However, the connect function in Python socket.io client is not activated. Here are the logs when the connection is established:

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

Meanwhile, the "chat message" and "disconnect" events work well and their functions are all activated, and the callback function also works.

Why is the connect function in Python socket.io client not activated when the socket.io connection is established? Did I miss anything? Please give me some feedback, thank you!

0

There are 0 answers