Comments (6)
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.
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.
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.
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!")
- response from server has to be received by client side event @sio_client.on('response')
and print the server response.
from python-socketio.
You can't use time.sleep
in an asyncio application because it is a blocking call. Use asyncio.sleep
instead.
from python-socketio.
oh ok, it works now, thanks for pointing out the mistake.
from python-socketio.
Related Issues (20)
- Clients never receive room emit - Gunicorn+Uvicorn/FastAPI/Redis with preload_app=True, workers>1 HOT 4
- In Python 3.12, AttributeError: 'called_once_with' is not a valid assertion HOT 3
- May need to remove "pip install aioredis" from the documentation
- 5.10.0: pytest is failing HOT 4
- `max_http_buffer_size` value seem ignored by the server HOT 14
- Implementing `__enter__`/`__exit__` on `Client` like `SimpleClient` HOT 2
- Request: type hints (e.g. for mypy) HOT 3
- sio.disconnect() will connect after a connection drop HOT 21
- Update documentation of usage with Gunicorn + gevent/eventlet HOT 5
- Wildcard / catch-all namespace for event handlers HOT 1
- Heroku Problems with Gevent (Request Timeout + Polling Hanging)
- Concurrent broadcasting HOT 2
- All connections stop processing events at the same time
- Session not found when using sio.transport(sid) due to wrong session id HOT 1
- _ping background task not cancelled by async_server.shutdown() HOT 1
- Option to reconnect on initial connection failure
- Value error : Invalid aysnc_mode specified HOT 2
- AsyncServer disconnect event not sent with `aiohttp>=3.9.0` HOT 2
- Test failure with .helpers import AsyncMock HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from python-socketio.