Git Product home page Git Product logo

Comments (6)

miguelgrinberg avatar miguelgrinberg commented on June 14, 2024

To get the sid assigned to a client for a given namespace, you should use the get_sid() method. The sid attribute is private, you should not use it.

from python-socketio.

manjeshshenoy avatar manjeshshenoy commented on June 14, 2024

Ok, now using get_sid() provides same sid on client side , so sid mismatch may not be the problem,
but the problem that i face is that client emits are not being received by the server. and there is a disconnect that happens after a minute, any suggestion on why this is happening.

server log

NFO: Uvicorn running on http://127.0.0.1:1112 (Press CTRL+C to quit)
INFO: Started reloader process [4100] using StatReload
db connected!
Server initialized for asgi.
Server initialized for asgi.
INFO: Started server process [16152]
INFO: Waiting for application startup.
INFO: Application startup complete.
uelWnfNVb960WH7-AAAA: Sending packet OPEN data {'sid': 'uelWnfNVb960WH7-AAAA', 'upgrades': [], 'pingTimeout': 20000, 'pingInterval': 25000}
uelWnfNVb960WH7-AAAA: Received request to upgrade to websocket
INFO: ('127.0.0.1', 57632) - "WebSocket /socket.io/?transport=websocket&EIO=4&t=1708310093.8300152" [accepted]
uelWnfNVb960WH7-AAAA: Upgrade to websocket successful
uelWnfNVb960WH7-AAAA: Received packet MESSAGE data 0{}
emitting event "response" to all [/]
uelWnfNVb960WH7-AAAA: Sending packet MESSAGE data 2["response","pIbKfi6FC1piUe9gAAAB"]
uelWnfNVb960WH7-AAAA: Sending packet MESSAGE data 0{"sid":"pIbKfi6FC1piUe9gAAAB"}
connected client pIbKfi6FC1piUe9gAAAB
service task canceled
uelWnfNVb960WH7-AAAA: Sending packet PING data None
disconnect client pIbKfi6FC1piUe9gAAAB

client code.

async def main():
    await sio_client.connect(url='http://127.0.0.1:1112',transports=['websocket'])
    print('my sid is', sio_client.get_sid())

    while True :
        await sio_client.emit('msg', 'client msg stream')

server code.

@sio_server.on('msg')
async def msg(sid, data):
    print("client :  ",str(data))


from python-socketio.

miguelgrinberg avatar miguelgrinberg commented on June 14, 2024

Please provide complete simplified versions of your client and your server. With the snippets that you shared I cannot really tell what's wrong.

from python-socketio.

manjeshshenoy avatar manjeshshenoy commented on June 14, 2024

I have provided the server.py and client.py code, please save the file with same name and run them in two different console.

requirements
pip install python-socketio uvicorn fastapi asyncio

python-socketio==5.11.1
uvicorn==0.27.1
fastapi==0.92.0
asyncio==3.4.3

# server Code -- server.py

import socketio
from fastapi import FastAPI
import  uvicorn

sio_server =socketio.AsyncServer(
    async_mode ='asgi',
    cors_allowed_origins='*',
    logger=True,
    engineio_logger=True,
)

sio_app = socketio.ASGIApp(
    socketio_server=sio_server
)

app =FastAPI()
app.mount('/',app=sio_app)

@sio_server.event
async def connect(sid, environ, auth):
    print('connected client', sid)
    await sio_server.emit('response', sid)


@sio_server.event
async def disconnect(sid):
    print('disconnect client', sid)


############  below custom events  - msg1 and msg2  are not working !!  ############
@sio_server.on('msg1')
async def msg1(sid, data):
    print("Msg receive from " +str(sid) +"and msg is : ",str(data))
    await sio_server.emit('response',"you are  smart 1!")


@sio_server.event
async def msg2(sid, data):
    print("Msg receive from " +str(sid) +"and msg is : ",str(data))
    await sio_server.emit('response',"you are  smart 2!")

#####################################################################################

@app.get('/')
async def home():
    return {'message' :  'Hello Developers'}


def main():
    try:
        uvicorn.run('server:app', reload=True,port=1112)
    finally:
        print("db disconnected!")

if __name__  =='__main__' :
    main()

# Client Code -- client.py


import socketio
import asyncio
import time

sio_client = socketio.AsyncClient( )


@sio_client.event
async  def connect():
    print('Connected to Server')


@sio_client.event
async  def disconnect():
    print('Disconnected from Server')



@sio_client.on('response')
async  def response(data):
     print(data)



async def main():

    await sio_client.connect(url='http://127.0.0.1:1112',transports=['websocket'])
    print('my sid is', sio_client.get_sid())

     
    while True :
        await sio_client.emit('msg1', 'How are you ?')
        time.sleep(1)
		await sio_client.emit('msg2', 'How are you ?')
		
    await sio_client.disconnect()

asyncio.run(main())

expectation is

1 . below two lines are executed in client side.

await sio_client.emit('msg1', 'How are you ?')
await sio_client.emit('msg2', 'How are you ?')

2 . server receives these emits.
and server respond with the below emits from msg1 and msg2 events.

await sio_server.emit('response',"you are smart 1!")
await sio_server.emit('response',"you are smart 2!")

  1. response from server has to be received by client side event @sio_client.on('response')
    and print the server response.

from python-socketio.

miguelgrinberg avatar miguelgrinberg commented on June 14, 2024

You can't use time.sleep in an asyncio application because it is a blocking call. Use asyncio.sleep instead.

from python-socketio.

manjeshshenoy avatar manjeshshenoy commented on June 14, 2024

oh ok, it works now, thanks for pointing out the mistake.

from python-socketio.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.