添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
https://stackoverflow.com/questions/15219858/how-to-store-a-complex-object-in-redis-using-redis-py obj = ExampleObject() pickled_object = pickle.dumps(obj) r.set('some_key', pickled_object) unpacked_object = pickle.loads(r.get('some_key')) obj == unpacked_object typing.Dict[key_type, value_type] from typing import List , Dict from fastapi import FastAPI , WebSocket , WebSocketDisconnect app = FastAPI ( ) class ConnectionManager : def __init__ ( self ) : # 存放激活的链接 self . active_connections : List [ Dict [ str , WebSocket ] ] = [ ] async def connect ( self , user : str , ws : WebSocket ) : await ws . accept ( ) self . active_connections . append ( { "user" : user , "ws" : ws } ) def disconnect ( self , user : str , ws : WebSocket ) : # 关闭时 移除ws对象 self . active_connections . remove ( { "user" : user , "ws" : ws } ) @ staticmethod async def send_personal_message ( message : dict , ws : WebSocket ) : # 发送个人消息 await ws . send_json ( message ) async def send_other_message ( self , message : dict , user : str ) : # 发送个人消息 for connection in self . active_connections : if connection [ "user" ] == user : await connection [ 'ws' ] . send_json ( message ) async def broadcast ( self , data : dict ) : # 广播消息 for connection in self . active_connections : await connection [ 'ws' ] . send_json ( data ) manager = ConnectionManager ( ) @app . websocket ( "/ws/{user}" ) async def websocket_endpoint ( ws : WebSocket , user : str ) : await manager . connect ( user , ws ) await manager . broadcast ( { "user" : user , "message" : "进入聊天" } ) try : while True : data = await ws . receive_json ( ) print ( data , type ( data ) ) send_user = data . get ( "send_user" ) if send_user : await manager . send_personal_message ( data , ws ) await manager . send_other_message ( data , send_user ) else : await manager . broadcast ( { "user" : user , "message" : data [ 'message' ] } ) except WebSocketDisconnect : manager . disconnect ( user , ws ) await manager . broadcast ( { "user" : user , "message" : "离开" } ) if __name__ == "__main__" : import uvicorn # 官方推荐是用命令后启动 uvicorn main:app --host=127.0.0.1 --port=8010 --reload uvicorn . run ( app = 'main:app' , host = "127.0.0.1" , port = 8010 , reload = True , debug = True )

客户端代码

由于只是demo, 所以代码都是固定的,有三份固定写的身份信息, 到时候客户端会有登录

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>聊天1</title>
</head>
<h1>User1 Chat</h1>
<form action="" onsubmit="sendMessage(event)">
    <input type="text" id="messageText" autocomplete="off"/>
    <button>Send</button>
</form>
<form action="" onsubmit="sendOtherMessage(event)">
    <input type="text" id="messageOther" autocomplete="off"/>
    <button>Send Other</button>
</form>
<ul id='messages'>
<script>
    let ws = new WebSocket("ws://127.0.0.1:8010/ws/user1");
    ws.onmessage = function(event) {
        let messages = document.getElementById('messages')
        let message = document.createElement('li');
        console.log(event.data, typeof (event.data), 2222)
        let receiveJson = JSON.parse(event.data);
        console.log(receiveJson, typeof (receiveJson), 333);
        let content = document.createTextNode(`${receiveJson.user}-${receiveJson.message}`);
        message.appendChild(content);
        messages.appendChild(message)
    function sendMessage(event) {
        let input = document.getElementById("messageText");
        let message = {message: input.value, user: "user1"};
        let messageJson = JSON.stringify(message);
        ws.send(messageJson);
        input.value = '';
        event.preventDefault()
    function sendOtherMessage(event) {
        let input = document.getElementById("messageOther");
        let message = {message: input.value, user: "user1", send_user: "user2"};
        let messageJson = JSON.stringify(message);
        ws.send(messageJson);
        input.value = '';
        event.preventDefault()
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>聊天2</title>
</head>
<h1>User2 Chat</h1>
<form action="" onsubmit="sendMessage(event)">
    <input type="text" id="messageText" autocomplete="off"/>
    <button>Send</button>
</form>
<form action="" onsubmit="sendOtherMessage(event)">
    <input type="text" id="messageOther" autocomplete="off"/>
    <button>Send Other</button>
</form>
<ul id='messages'>
<script>
    let ws = new WebSocket("ws://127.0.0.1:8010/ws/user2");
    ws.onmessage = function(event) {
        let messages = document.getElementById('messages')
        let message = document.createElement('li');
        console.log(event.data, typeof (event.data), 2222)
        let receiveJson = JSON.parse(event.data);
        console.log(receiveJson, typeof (receiveJson), 333);
        let content = document.createTextNode(`${receiveJson.user}-${receiveJson.message}`);
        message.appendChild(content);
        messages.appendChild(message)
    function sendMessage(event) {
        let input = document.getElementById("messageText")
        let message = {message: input.value, user: "user2"}
        let messageJson = JSON.stringify(message);
        ws.send(messageJson);
        input.value = '';
        event.preventDefault()
    function sendOtherMessage(event) {
        let input = document.getElementById("messageOther");
        let message = {message: input.value, user: "user2", send_user: "user1"};
        let messageJson = JSON.stringify(message);
        ws.send(messageJson);
        input.value = '';
        event.preventDefault()
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>聊天3</title>
</head>
<h1>User3 Chat</h1>
<form action="" onsubmit="sendMessage(event)">
    <input type="text" id="messageText" autocomplete="off"/>
    <button>Send</button>
</form>
<ul id='messages'>
<script>
    let ws = new WebSocket("ws://127.0.0.1:8010/ws/user3");
    ws.onmessage = function(event) {
        let messages = document.getElementById('messages')
        let message = document.createElement('li');
        console.log(event.data, typeof (event.data), 2222)
        let receiveJson = JSON.parse(event.data);
        console.log(receiveJson, typeof (receiveJson), 333);
        let content = document.createTextNode(`${receiveJson.user}-${receiveJson.message}`);
        message.appendChild(content);
        messages.appendChild(message)
    function sendMessage(event) {
        let input = document.getElementById("messageText")
        let message = {message: input.value, user: "user3"}
        let messageJson = JSON.stringify(message);
        ws.send(messageJson);
        input.value = '';
        event.preventDefault()
</script>
</body>
</html>

websocket 的基本使用原理就是这样了, 全双工的传输协议真的很方便。

FastAPI WebSocket 分组发送Json数据用户1和 用户2 可以互相发送私信消息用户1 2 3之间相当于一个群,可以发送广播消息效果代码FastAPI 服务端代码#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2020/8/19 13:38# @Author : CoderCharm# @File : main.py# @Software: PyCharm# @Github : g
Websocket示例 作者:卞荣成作者博客:作者网站: 本项目采用“保持署名—非商用”创意共享4.0许可证。只要保持原作者署名和非商用,您可以自由地阅读、分享、修改。详细的法律条文请参见网站。 1、在cmd中运行命令 node simpleWSserver.js 2、访问页面:simpleclient.html
from redis import StrictRedis from fastapi import FastAPI from fastapi.testclient import TestClient from fastapi.websockets import WebSocket app = FastAPI() r = StrictRedis( define(['backend'], function (Backend) { var socket; //websocket的实例 var lockReconnect = false; //避免重复连接 reconnect(); function getwebsock...
感谢大神顺川页​www.zhihu.com的帮助,我才会上传任意多个文件。现在我要写一个接口,需要同时上传几个文件(图像文件),同时也要传一些参数(设备ID和拍摄时间),服务器的代码好写,但客户端的代码就不容易传参。趟过的坑,记录一下。服务器代码:from typing import List from fastapi import FastAPI,Form,UploadFile app = Fa...
ps:127.0.0.1:8000 127.0.0.1:8000/docs【Swagger UI 提供的api文档】 127.0.0.1:8000/redoc【ReDoc 提供的api文档】 2.指定数据类型的路径参数 3.枚举路径参数 4.匹配所有路径 5.普通传参 6.必备参数 调用.................................... 2. 客户端连接成功后,服务器端会创建一个WebSocket会话对象,可以通过该对象向客户端发送消息。 3. 在Java中,可以使用JSON库来生成和解析JSON数据。例如,使用Gson库可以将Java对象转换为JSON字符串,或将JSON字符串转换为Java对象。 4. 在服务器端,可以使用WebSocket会话对象的getBasicRemote()方法获取一个RemoteEndpoint.Basic对象,通过该对象可以向客户端发送消息。 5. 在客户端,可以使用JavaScript的WebSocket API来连接WebSocket服务器,并通过WebSocket对象的send()方法发送消息。接收到消息后,可以通过WebSocket对象的onmessage()方法处理消息。 下面是一个简单的Java WebSocket示例,演示如何发送JSON数据: ```java import com.google.gson.Gson; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.HashMap; import java.util.Map; @ServerEndpoint("/websocket") public class WebSocketServer { private static Map<Session, String> clients = new HashMap<>(); @OnOpen public void onOpen(Session session) { System.out.println("WebSocket opened: " + session.getId()); clients.put(session, ""); @OnMessage public void onMessage(String message, Session session) { System.out.println("WebSocket message received: " + message); Gson gson = new Gson(); Message msg = gson.fromJson(message, Message.class); clients.put(session, msg.getUsername()); broadcast(gson.toJson(msg)); @OnClose public void onClose(Session session) { System.out.println("WebSocket closed: " + session.getId()); clients.remove(session); @OnError public void onError(Throwable error) { System.out.println("WebSocket error: " + error.getMessage()); private void broadcast(String message) { for (Session session : clients.keySet()) { try { session.getBasicRemote().sendText(message); } catch (IOException e) { e.printStackTrace(); private static class Message { private String username; private String content; public String getUsername() { return username; public void setUsername(String username) { this.username = username; public String getContent() { return content; public void setContent(String content) { this.content = content; 在上面的示例中,我们定义了一个WebSocket服务器端,监听"/websocket"路径的连接请求。当客户端连接成功后,服务器端会创建一个WebSocket会话对象,并将其保存到clients集合中。当客户端发送消息时,服务器端会将消息解析为一个Message对象,并将其转换为JSON字符串,然后通过WebSocket会话对象的getBasicRemote()方法向所有客户端发送消息。当客户端断开连接时,服务器端会将其从clients集合中移除。 在客户端,可以使用以下代码连接WebSocket服务器,并发送JSON数据: ```javascript var socket = new WebSocket("ws://localhost:808/websocket"); socket.onopen = function(event) { console.log("WebSocket opened"); socket.onmessage = function(event) { console.log("WebSocket message received: " + event.data); var msg = JSON.parse(event.data); // 处理接收到的消息 socket.onclose = function(event) { console.log("WebSocket closed"); socket.onerror = function(event) { console.log("WebSocket error: " + event.message); function sendMessage(username, content) { var msg = { username: username, content: content socket.send(JSON.stringify(msg)); 在上面的代码中,我们使用WebSocket API连接WebSocket服务器,并定义了四个事件处理函数:onopen、onmessage、onclose和onerror。当WebSocket连接成功时,会调用onopen函数;当接收到消息时,会调用onmessage函数;当WebSocket连接关闭时,会调用onclose函数;当WebSocket发生错误时,会调用onerror函数。我们还定义了一个sendMessage函数,用于向服务器发送JSON数据。在接收到消息时,我们可以通过JSON.parse()方法将JSON字符串解析为JavaScript对象,然后进行处理。 希望这个示例能够帮助你实现Java WebSocket发送JSON数据,并在前端JavaScript接收JSON数据的功能。