Skip to navigation
Test websocket with FASTAPI
07.07.21
fastapi: import fastapi from fastapi import WebSocket from fastapi_utils.cbv import cbv from typing import Optional router = fastapi.APIRouter() # test here: https://www.websocket.org/echo.html @router.websocket("/log_mail") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") javascript: var log = new Log2textarea("logger2"); window.onload = async function () { log.info("...start websocket"); //let socket = new WebSocket("wss://javascript.info/article/websocket/demo/hello"); //let socket = new WebSocket("ws://localhost:8071/log/mail"); let url = "ws://127.0.0.1:8071/log_mail"; let socket = new WebSocket(url); log.info(url); socket.onopen = function(e) { log.info("[open] Connection established"); log.info("Sending to server"); socket.send("My name is foo"); }; socket.onmessage = function(event) { log.info(`[message] Data received from server: ${event.data}`); }; socket.onclose = function(event) { if (event.wasClean) { log.info(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`); } else { // e.g. server process killed or network down // event.code is usually 1006 in this case log.info('[close] Connection died'); } }; socket.onerror = function(error) { log.info(`[error] ${error.message}`); }; }; //or test here //https://www.websocket.org/echo.html
https://www.websocket.org/echo.html
Reply
Anonymous
Information Epoch 1732545689
The sum of the parts if greater than the whole.
Home
Notebook
Contact us