5

I have a Python server using Flask, that has a websocket connection using Flask-SocketIO . There is a similar question : Send custom data along with handshakeData in socket.io? The idea is to do the same thing but instead of using Node, using Flask. I want the client to send some data in the connect event, for example:

var socket = io("http://127.0.0.1:3000/", { query: "foo=bar" });

I haven't been able to get that custom data, and I can't rely on cookies due to the client's framework. A working solution is to have the connect event as usual, and then, in a custom event, get that information as a payload. But what we would want is to only have to do a connect event. Thanks!

Community
  • 1
  • 1

3 Answers3

5

As Miguel suggested in his comment you can simply do

from flask import Flask
from flask import request

app = Flask(__name__)
socketio = SocketIO(app)

@socketio.on('connect')
def connect():
    foo = request.args.get('foo')
    # foo will be 'bar' when a client connects

socketio.run(app)

on the server side.

Robsdedude
  • 1,292
  • 16
  • 25
0

The global connect method gets called on server side. But not my connect method for a specific namespace. Are namespaces supporting query parameter?

Client Code

const socket = io.connect('http://127.0.0.1:5000/ds', { query: {name: "Test"} });

Server Code

@socketio.on('connect', namespace='/ds')
def test_connect():
    foo = request.args.get('foo')
    print("CONNECT DS")
Manuel
  • 319
  • 4
  • 14
  • The danger with this is that the query variables can be cached by servers so you do not want to send your sensitive data in the URL – TheRealChx101 Nov 20 '19 at 01:27
0

as of this time in 2021 you can send Auth data from python-socketio client with

sio.connect('http://localhost:6000/',auth={"authToken":"some auth token"})

Mohamed Emad
  • 123
  • 1
  • 14