wordpress修改我要注册链接,seo新人培训班,网站建设门户,丝印网版制作1. Websocket
1.1 Websocket介绍 WebSocket 是一种在单个TCP连接上进行全双工通信的协议#xff0c;允许客户端和服务器之间相互发送数据#xff0c;而不需要像传统的HTTP请求-响应模型那样频繁建立和断开连接。 全双工通信(Full-Duplex Communication)是一种通信模式#…1. Websocket
1.1 Websocket介绍 WebSocket 是一种在单个TCP连接上进行全双工通信的协议允许客户端和服务器之间相互发送数据而不需要像传统的HTTP请求-响应模型那样频繁建立和断开连接。 全双工通信(Full-Duplex Communication)是一种通信模式允许通信双方同时发送和接收数据。换句话说数据可以同时从两端双向传输而不会相互阻塞或干扰。
1.2 FastAPI中的Websocket FastAPI提供了对WebSocket的原生支持允许你轻松构建高效的实时应用如聊天室、实时数据更新等。
1.2.1 装饰器 FastAPI中与WebSocket相关的主要装饰器为 app.websocket。该装饰器的作用和参数如下
作用将一个路径(如/ws)与一个处理WebSocket请求的函数关联。当客户端通过WebSocket连接该路径时FastAPI会调用该函数处理连接和通信。参数它接受的参数与其他路由装饰器相同主要是路径(URL)可选地也能设置依赖项、权限等。
代码举例如下(当客户端通过WebSocket连接/ws路径时FastAPI将执行下面的websocket_endpoint函数)
from fastapi import FastAPI, WebSocket
app FastAPI()
# 定义一个 WebSocket 路由
app.websocket(/ws)
async def websocket_endpoint(websocket: WebSocket):await websocket.accept() # 接受 WebSocket 连接while True:data await websocket.receive_text() # 接收来自客户端的消息await websocket.send_text(fMessage text was: {data}) # 回复消息给客户端1.2.2 websocket相关方法 FastAPI提供了处理WebSocket各种事件的方法包括接受消息、发送消息、关闭连接等。具体如下
websocket.accept接受WebSocket连接请求。websocket.receive_text接收客户端发来的文本消息。websocket.send_text向客户端发送文本消息。websocket.close关闭WebSocket连接。
2. 构建对话机器人 这里我们用FastAPI和React构建一个聊天机器人。这里关于机器人的后端处理逻辑这里不做详细介绍(这里不介绍CSS代码)。具体代码如下 React中App.tsx代码如下
import ./App.css;
import ChatPage from ./components/ChatPage;function App() {return (div classNameAppdiv classNameheaderdiv classNameheader-logoimg srchttps://cdn.builder.io/api/v1/image/assets/TEMP/b0db057162d379f22892cd5ae4d13c509717e0a81da39be3f65cb94e15556ed7?apiKey0682bce60b3549f085131079f1bf89f0apiKey0682bce60b3549f085131079f1bf89f0 altChainlit / div classNameheader-titleSmartRecommend服务推荐助手/div/div/divdiv classNamebody-containerdiv classNamemaindiv classNamechatpageChatPage //div/div/div/div);
}
export default App;React中ChatPage.tsx代码如下:
import ./ChatPage.css;
import { useEffect, useState} from react;
import { nanoid } from nanoid;interface Message{id:string,name:string,type:string,output:string,createdAt:number|string,
}
function ChatPage() {const [inputValue, setInputValue] useState();const [messages,setMessages] useStateMessage[]([]);const [socket,setSocket] useStateWebSocket|null(null);useEffect(() {const ws new WebSocket(ws://localhost:8000/ws/chat);ws.onopen () {console.log(websocket链接已建立!);};ws.onmessage (event) {const message JSON.parse(event.data);setMessages((prevMessages) [...prevMessages, message]);};ws.onerror (error) {console.log(WebSocket错误:, error);};ws.onclose(){console.log(websocket链接已关闭!);}setSocket(ws);return () {ws.close();}},[]);const handleSendMessage () {const content inputValue.trim();if (content) {const message: Message{id: nanoid(),name: User,type: user_message,output: content,createdAt: Date.now(),};setMessages((prevMessages) [...prevMessages, message]);socket?.send(JSON.stringify(message));}setInputValue();};const renderMessage (message:Message,index:number) {const dateOptions: Intl.DateTimeFormatOptions {hour: 2-digit,minute: 2-digit,};const date new Date(message.createdAt).toLocaleTimeString(undefined,dateOptions);if(message.type user_message) {return (div key{message.id} classNamechat-box-userdiv classNameuser-avatarU/divdiv classNamebot-user-contentdiv classNameuser-icondiv classNamebot-user-name{message.name}/divdiv classNamebot-user-time{date}/div/divdiv classNameuser-chat-message{message.output}/div/div/div);} else {return (div key{message.id} classNamechat-box-botdiv classNamebot-avatarB/divdiv classNamebot-user-contentdiv classNamebot-icondiv classNamebot-user-name{message.name}/divdiv classNamebot-user-time{date}/div/divdiv classNamebot-chat-message{message.output}/div/div/div);};};return (div classNamechat-containerdiv classNamechat-box{messages.map(renderMessage)}/divdiv classNamefixed-bottominput classNamefixed-bottom-input typetextvalue{inputValue}placeholder你可以输入“金仔金仔”唤醒服务onChange{(e) setInputValue(e.target.value)}onKeyUp{(e) {if (e.key Enter) {handleSendMessage();}}}/inputbutton onClick{handleSendMessage} classNamebutton typesubmitSend/button/div/div);
}
export default ChatPage;后端FastAPI代码
from fastapi import FastAPI, WebSocket,HTTPException
import uvicorn
from fastapi.middleware.cors import CORSMiddleware
from typing import List
import json
import datetime
from nanoid import generate
import httpxappFastAPI()
app.add_middleware(CORSMiddleware,allow_origins[http://localhost:3000],allow_credentialsTrue,allow_methods[*],allow_headers[*],
)
clients: List[WebSocket] []RASA_API_URLhttp://localhost:5005/webhooks/rest/webhookapp.websocket(/ws/chat)
async def websocket_endpoint(websocket: WebSocket):await websocket.accept()clients.append(websocket)try:while True:data await websocket.receive_text()for client in clients:text{id: generate(),name:Bot,type:bot_message,output:json.loads(data)[output],createdAt:int(datetime.datetime.now().timestamp()*1000)}textjson.dumps(text)await client.send_text(text)except Exception as e:print(e)clients.remove(websocket)if __name__ __main__:uvicorn.run(app, host0.0.0.0, port8000)
文章转载自: http://www.morning.cwkcq.cn.gov.cn.cwkcq.cn http://www.morning.rtsd.cn.gov.cn.rtsd.cn http://www.morning.yntsr.cn.gov.cn.yntsr.cn http://www.morning.srndk.cn.gov.cn.srndk.cn http://www.morning.pcgmw.cn.gov.cn.pcgmw.cn http://www.morning.wwthz.cn.gov.cn.wwthz.cn http://www.morning.dfffm.cn.gov.cn.dfffm.cn http://www.morning.pwmpn.cn.gov.cn.pwmpn.cn http://www.morning.pnntx.cn.gov.cn.pnntx.cn http://www.morning.fbpyd.cn.gov.cn.fbpyd.cn http://www.morning.sgfgz.cn.gov.cn.sgfgz.cn http://www.morning.sdecsd.cn.gov.cn.sdecsd.cn http://www.morning.xknsn.cn.gov.cn.xknsn.cn http://www.morning.pxdgy.cn.gov.cn.pxdgy.cn http://www.morning.kkgbs.cn.gov.cn.kkgbs.cn http://www.morning.rtsx.cn.gov.cn.rtsx.cn http://www.morning.qfqld.cn.gov.cn.qfqld.cn http://www.morning.thrtt.cn.gov.cn.thrtt.cn http://www.morning.tsdqr.cn.gov.cn.tsdqr.cn http://www.morning.qnftc.cn.gov.cn.qnftc.cn http://www.morning.jbpodhb.cn.gov.cn.jbpodhb.cn http://www.morning.mmjqk.cn.gov.cn.mmjqk.cn http://www.morning.dycbp.cn.gov.cn.dycbp.cn http://www.morning.webpapua.com.gov.cn.webpapua.com http://www.morning.xwzsq.cn.gov.cn.xwzsq.cn http://www.morning.prysb.cn.gov.cn.prysb.cn http://www.morning.vvbsxm.cn.gov.cn.vvbsxm.cn http://www.morning.pqndg.cn.gov.cn.pqndg.cn http://www.morning.brrxz.cn.gov.cn.brrxz.cn http://www.morning.pzrnf.cn.gov.cn.pzrnf.cn http://www.morning.guanszz.com.gov.cn.guanszz.com http://www.morning.rnpnn.cn.gov.cn.rnpnn.cn http://www.morning.jzykq.cn.gov.cn.jzykq.cn http://www.morning.xkwrb.cn.gov.cn.xkwrb.cn http://www.morning.mdwlg.cn.gov.cn.mdwlg.cn http://www.morning.krkwh.cn.gov.cn.krkwh.cn http://www.morning.pqkrh.cn.gov.cn.pqkrh.cn http://www.morning.pudejun.com.gov.cn.pudejun.com http://www.morning.wmhqd.cn.gov.cn.wmhqd.cn http://www.morning.tbjb.cn.gov.cn.tbjb.cn http://www.morning.jtszm.cn.gov.cn.jtszm.cn http://www.morning.ndlww.cn.gov.cn.ndlww.cn http://www.morning.sryyt.cn.gov.cn.sryyt.cn http://www.morning.hslgq.cn.gov.cn.hslgq.cn http://www.morning.slfmp.cn.gov.cn.slfmp.cn http://www.morning.wnjsp.cn.gov.cn.wnjsp.cn http://www.morning.grqlc.cn.gov.cn.grqlc.cn http://www.morning.syssdz.cn.gov.cn.syssdz.cn http://www.morning.sxhdzyw.com.gov.cn.sxhdzyw.com http://www.morning.jzykq.cn.gov.cn.jzykq.cn http://www.morning.mlckd.cn.gov.cn.mlckd.cn http://www.morning.cnfxr.cn.gov.cn.cnfxr.cn http://www.morning.haibuli.com.gov.cn.haibuli.com http://www.morning.jcffp.cn.gov.cn.jcffp.cn http://www.morning.nsppc.cn.gov.cn.nsppc.cn http://www.morning.lffbz.cn.gov.cn.lffbz.cn http://www.morning.psqs.cn.gov.cn.psqs.cn http://www.morning.mrnnb.cn.gov.cn.mrnnb.cn http://www.morning.fqpyj.cn.gov.cn.fqpyj.cn http://www.morning.rnwmp.cn.gov.cn.rnwmp.cn http://www.morning.nqbs.cn.gov.cn.nqbs.cn http://www.morning.twdwy.cn.gov.cn.twdwy.cn http://www.morning.ydflc.cn.gov.cn.ydflc.cn http://www.morning.qbgff.cn.gov.cn.qbgff.cn http://www.morning.zlxkp.cn.gov.cn.zlxkp.cn http://www.morning.xrlwr.cn.gov.cn.xrlwr.cn http://www.morning.rynqh.cn.gov.cn.rynqh.cn http://www.morning.gtnyq.cn.gov.cn.gtnyq.cn http://www.morning.clqpj.cn.gov.cn.clqpj.cn http://www.morning.qytby.cn.gov.cn.qytby.cn http://www.morning.kyfrl.cn.gov.cn.kyfrl.cn http://www.morning.qpmmg.cn.gov.cn.qpmmg.cn http://www.morning.rbtny.cn.gov.cn.rbtny.cn http://www.morning.czgfn.cn.gov.cn.czgfn.cn http://www.morning.mgzjz.cn.gov.cn.mgzjz.cn http://www.morning.jbhhj.cn.gov.cn.jbhhj.cn http://www.morning.ypzr.cn.gov.cn.ypzr.cn http://www.morning.bnzjx.cn.gov.cn.bnzjx.cn http://www.morning.gcjhh.cn.gov.cn.gcjhh.cn http://www.morning.slysg.cn.gov.cn.slysg.cn