Skip to content

Commit

Permalink
Working websockets
Browse files Browse the repository at this point in the history
  • Loading branch information
JJMN22 committed Mar 23, 2024
1 parent 0481690 commit 0948061
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 47 deletions.
48 changes: 15 additions & 33 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,18 @@
from flask import Flask, render_template
from flask_socketio import SocketIO, send, emit
from fastapi import FastAPI, WebSocket
from starlette.websockets import WebSocketDisconnect

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

@app.route('/')
def index():
return render_template('iotest.html')
@app.get("/")
async def root():
return {"message": "Hello, world!"}

def background_task():
"""Example of how to send server generated events to clients."""
count = 0
while True:
socketio.sleep(10) # Use socketio.sleep, not time.sleep!
count += 1
socketio.emit('message', 'heartbeat', namespace='/')
print("Message sent from the server.")

@socketio.on('message')
def handle_message(message):
print('received message: ' + message)
send(message)

@socketio.on('connect')
def handle_connect():
print('Client connected')
emit('after connect', {'data':'Lets dance'})
socketio.start_background_task(background_task)

@socketio.on('disconnect')
def handle_disconnect():
print('Client disconnected')

if __name__ == '__main__':
socketio.run(app, debug=True)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
try:
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
except WebSocketDisconnect:
print("Client disconnected")
28 changes: 14 additions & 14 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
bidict==0.23.1
blinker==1.7.0
annotated-types==0.6.0
anyio==4.3.0
click==8.1.7
dnspython==2.6.1
eventlet==0.35.2
Flask==3.0.2
Flask-SocketIO==5.3.6
fastapi==0.110.0
gevent==24.2.1
greenlet==3.0.3
h11==0.14.0
itsdangerous==2.1.2
Jinja2==3.1.3
MarkupSafe==2.1.5
python-engineio==4.9.0
python-socketio==5.11.1
simple-websocket==1.0.0
Werkzeug==3.0.1
wsproto==1.2.0
idna==3.6
pydantic==2.6.4
pydantic_core==2.16.3
sniffio==1.3.1
starlette==0.36.3
typing_extensions==4.10.0
uvicorn==0.29.0
websocket==0.2.1
zope.event==5.0
zope.interface==6.2
7 changes: 7 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
var ws = new WebSocket("ws://127.0.0.1:8000/ws");
ws.onmessage = function(event) {
console.log("Received:", event.data);
};
ws.onopen = function(event) {
ws.send("Hello Server!");
};

0 comments on commit 0948061

Please sign in to comment.