Last active
June 7, 2022 16:26
-
-
Save vatsalsaglani/c6421cee8c4df7c75fd8b9bc09376dc4 to your computer and use it in GitHub Desktop.
FastAPI WebSocket & JS WS with headers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import List | |
from fastapi import FastAPI, Header, WebSocket, WebSocketDisconnect | |
import uvicorn | |
app = FastAPI() | |
class ConnectionManager: | |
def __init__(self): | |
self.active_connections: List[WebSocket] = [] | |
async def connect(self, websocket: WebSocket): | |
await websocket.accept() | |
self.active_connections.append(websocket) | |
def disconnect(self, websocket: WebSocket): | |
self.active_connections.remove(websocket) | |
async def send_personal_message(self, message: str, websocket: WebSocket): | |
await websocket.send_text(message) | |
async def broadcast(self, message: str): | |
for connection in self.active_connections: | |
await connection.send_text(message) | |
manager = ConnectionManager() | |
@app.get("/") | |
async def get(): | |
return {"things": "cool"} | |
@app.websocket("/ws/classify-action") | |
async def websocket_endpoint(websocket: WebSocket, Custom: str = Header(str)): | |
await manager.connect(websocket) | |
if Custom == "1234": | |
print(f'HEADER and Matches AVAILABLE CONNECT: {Custom}') | |
# print(f'CLIENT: {client_id}') | |
try: | |
while True: | |
data = await websocket.receive_text() | |
await manager.send_personal_message(f"You wrote: {data}", websocket) | |
# await manager.broadcast(f"Client #{client_id} says: {data}") | |
except WebSocketDisconnect: | |
manager.disconnect(websocket) | |
# await manager.broadcast(f"Client #{client_id} left the chat") | |
else: | |
print(f'NO HEADER DISCONNECT') | |
# await websocket.send_json({"message": "Error", "status": False}) | |
await manager.send_personal_message("FAIL", websocket) | |
await websocket.close(code = 3000, reason = "Headers don't match") | |
manager.disconnect(websocket) | |
if __name__ == "__main__": | |
uvicorn.run(app) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { exit } = require("process"); | |
const WebSocket = require("ws"); | |
const ws = new WebSocket("ws://localhost:8000/ws/classify-action", features = {headers: {Custom: "1234"}}) | |
const readline = require("readline").createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}) | |
let is_read = true; | |
const send_message = (ws) => { | |
console.log("\nSEND MSG") | |
readline.question("\nEnter your message: ,", (msg) => { | |
ws.send(msg); | |
}) | |
ws.on("message", (data) => { | |
// console.log(data.toString()) | |
// console.log(parseString(data)) | |
if (data.toString() === "FAIL") { | |
console.log("\nCLOSING") | |
ws.close() | |
console.log("\CLOSED") | |
is_read = false | |
exit() | |
} else { | |
console.log("%s", data) | |
send_message(ws) | |
} | |
}) | |
} | |
ws.on("open", () => { | |
if (is_read) { | |
send_message(ws) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment