Home > Backend Development > Python Tutorial > How to use WebSocket in FastAPI for two-way communication

How to use WebSocket in FastAPI for two-way communication

PHPz
Release: 2023-07-29 22:12:22
Original
3575 people have browsed it

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
Copy after login

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}")
Copy after login

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
Copy after login

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连接已关闭');
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template