How to use WebSocket in FastAPI for two-way communication
How to use WebSocket for two-way communication in FastAPI
Introduction:
WebSocket is a protocol that enables two-way communication in web applications. Unlike the traditional HTTP request-response model, WebSocket allows the server to send messages directly to the client without the client explicitly initiating a request. In FastAPI, we can easily use WebSocket to achieve real-time two-way communication. This article will introduce how to use WebSocket in FastAPI to achieve two-way communication, with code examples.
Step 1: Install FastAPI and uvicorn
First, we need to make sure that Python 3.7 or higher is installed. Then, we can use pip to install FastAPI and uvicorn:
pip install fastapi uvicorn
Step 2: Create a FastAPI application
Next, we can create a FastAPI application. In a new .py file, add the following code:
from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message received: {data}")
The above code creates a FastAPI application and defines a websocket_endpoint function to handle WebSocket connections. In this function, we first call await websocket.accept()
to accept the WebSocket connection. We then use an infinite loop to continuously listen for messages being sent from the client. Once the message is received, we use await websocket.send_text()
to send the reply message back to the client.
Step 3: Start the application
We can use the uvicorn command to start the FastAPI application. Execute the following command in the terminal:
uvicorn main:app --reload
This will start a local server and listen on http://localhost:8000
.
Step 4: Test the WebSocket connection
Using any WebSocket client tool (such as the browser's developer tools or Postman), we can test the WebSocket connection. Open the WebSocket client tool and establish a connection to ws://localhost:8000/ws
.
Once the connection is successfully established, we can send messages to the server. The server will reply to the client with the received message.
Code example:
The following is a code example using JavaScript to send and receive messages through a WebSocket connection:
const socket = new WebSocket('ws://localhost:8000/ws'); socket.onopen = () => { console.log('WebSocket连接已建立'); socket.send('Hello, server!'); }; socket.onmessage = (event) => { console.log('收到服务器的消息:', event.data); }; socket.onclose = () => { console.log('WebSocket连接已关闭'); };
This code uses the WebSocket API to establish a connection and listen for the connection The opening, message receiving and connection closing events. When the connection is opened, send a message to the server. When receiving a message from the server, print the message content. When the connection is closed, print a connection closed message.
Conclusion:
Through the above steps, we can use WebSocket in FastAPI to achieve two-way communication. We can use the WebSocket
class provided by FastAPI to process and manage WebSocket connections to achieve real-time two-way communication. In this article, we also include a JavaScript code example that demonstrates how to send and receive messages using a WebSocket connection. I hope this article will help you understand and apply WebSocket technology.
The above is the detailed content of How to use WebSocket in FastAPI for two-way communication. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











With the continuous development of Internet technology, real-time communication has become an indispensable part of daily life. Efficient, low-latency real-time communication can be achieved using WebSockets technology, and PHP, as one of the most widely used development languages in the Internet field, also provides corresponding WebSocket support. This article will introduce how to use PHP and WebSocket to achieve real-time communication, and provide specific code examples. 1. What is WebSocket? WebSocket is a single

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

With the continuous development of Internet technology, real-time video streaming has become an important application in the Internet field. To achieve real-time video streaming, the key technologies include WebSocket and Java. This article will introduce how to use WebSocket and Java to implement real-time video streaming playback, and provide relevant code examples. 1. What is WebSocket? WebSocket is a protocol for full-duplex communication on a single TCP connection. It is used on the Web

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

PHP and WebSocket: Best Practice Methods for Real-Time Data Transfer Introduction: In web application development, real-time data transfer is a very important technical requirement. The traditional HTTP protocol is a request-response model protocol and cannot effectively achieve real-time data transmission. In order to meet the needs of real-time data transmission, the WebSocket protocol came into being. WebSocket is a full-duplex communication protocol that provides a way to communicate full-duplex over a single TCP connection. Compared to H

How to use Java and WebSocket to implement real-time stock quotation push Introduction: With the rapid development of the Internet, real-time stock quotation push has become one of the focuses of investors. The traditional stock market push method has problems such as high delay and slow refresh speed. For investors, the inability to obtain the latest stock market information in a timely manner may lead to errors in investment decisions. Real-time stock quotation push based on Java and WebSocket can effectively solve this problem, allowing investors to obtain the latest stock price information as soon as possible.

In this article, we will compare Server Sent Events (SSE) and WebSockets, both of which are reliable methods for delivering data. We will analyze them in eight aspects, including communication direction, underlying protocol, security, ease of use, performance, message structure, ease of use, and testing tools. A comparison of these aspects is summarized as follows: Category Server Sent Event (SSE) WebSocket Communication Direction Unidirectional Bidirectional Underlying Protocol HTTP WebSocket Protocol Security Same as HTTP Existing security vulnerabilities Ease of use Setup Simple setup Complex performance Fast message sending speed Affected by message processing and connection management Message structure Plain text or binary Ease of use Widely available Helpful for WebSocket integration
