rust学习基于tokio_actor聊天服务器实战(一 )

2024-02-01 08:28

本文主要是介绍rust学习基于tokio_actor聊天服务器实战(一 ),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言
tokio是Rust中使用最广泛的异步Runtime,它性能高、功能丰富、便于使用,是使用Rust实现高并发不可不学的一个框架
Actor 背后的基本思想是产生一个独立的任务,该任务独立于程序的其他部分执行某些工作。 通常,这些参与者通过使用消息传递信道与程序的其余部分进行通信。 由于每个 Actor 独立运行,因此使用它们设计的程序自然是并行的。 Actor 的一个常见用法是为 Actor 分配你要共享的某些资源的专有所有权,然后让其他任务通过与 Actor 通信来间接访问彼此的资源。 例如,如果要实现聊天服务器,则可以为每个连接生成一个任务,并在其他任务之间路由一个聊天消息的主任务。 十分有用,因为主任务可以避免必须处理网络IO,而连接任务可以专门处理网络IO;
为什么一定要用actor,这里只是仿照go项目里一部分,go 用的就是actor;

1:环境
rust1.75
ide rustrover64

2:设计及实现
这里使用类似单点登录模式,
useractor
先看go的
在这里插入图片描述
在这里插入图片描述
一共3个协程/future
接受网络消息 一个协程/future
发送网络消息 一个协程/future
逻辑处理 一个协程/future
协程/future间通信 直接用mpsc

world actor/accmgr 管理useractor 登录,踢人,广播等

一共1个协程/future 处理逻辑消息
在这里插入图片描述

rust 版
useractor
说明 receiver: mpsc::UnboundedReceiver, logic future 接受消息并处理
sendclient: mpsc::UnboundedSender 发送消息给 网络future 从而发送给前端
worldsender: mpsc::UnboundedSender, 跟world actor 通信接口

pub enum ActorMessage {synmsgwaitrep {//同步等待回复//需要发送到别处等到别处返回结果,类似于同步操作,只是异步执行的  //oneshot  spscrespond_to: crate::synMsgWaitRep, //同步消息},wtc_userchann {respond_to: crate::userChan_WTC, //},wtc_msg(sendMsgAndType),wtc_forwardmsg(sendMsgAndType), //直接转发 datactw_msg(sendMsgAndType),ctc_nettologic_msg(sendMsgAndType), //网络消息 to logicctc_logictonet_msg(sendMsgAndType), //logic to net  sendctc_signal_event(signalType),ctw_signal_event(signalType),wtc_signal_event(signalType),wtc_getChan_msg(userChannChann),
}
pub struct MyUserActor {connid: ConnectID,userid: UserID,username: String,guildid: GuildID,userstate: Arc<AtomicU8>,receiver: mpsc::UnboundedReceiver<ActorMessage>,sendclient: mpsc::UnboundedSender<VU8>,worldsender: mpsc::UnboundedSender<ActorMessage>,msgmask: u32,lasttime: [u32; ChatChannel_Num],
}

world actor
mpscrecv: mpsc::UnboundedReceiver, 接收ActorMessage logic future
chanchan: mpsc::UnboundedReceiver, 接受 ActorMessage2 logic future

pub enum ActorMessage2 {synmsgwaitrep {//同步等待回复//需要发送到别处等到别处返回结果,类似于同步操作,只是异步执行的  //oneshot  spscrespond_to: crate::synMsgWaitRep2, //同步消息},ctw_userhann {respond_to: crate::userChan_CTW, //同步消息},
}
pub struct userSendChanActorMessage {pub(crate) chanchan: Option<mpsc::UnboundedSender<ActorMessage>>,pub(crate) username: String,pub(crate) userguildid: GuildID,pub(crate) connectid: ConnectID,pub(crate) chanState: Arc<AtomicU8>, //user 状态
}pub struct worldActor {sharestate: Arc<AtomicU8>,mpscrecv: mpsc::UnboundedReceiver<ActorMessage>,chanchan: mpsc::UnboundedReceiver<ActorMessage2>,usermap: HashMap<UserID, userChan_world>,namemap: HashMap<String, UserID>,guildmap: HashMap<GuildID, HashSet<UserID>>,maxonlinerole: u32,
}async fn run(mut self) {// let logic_handle = self.handle_logic(recv);loop {tokio::select! {recvmsg= self.mpscrecv.recv()=> {if let Some(actmsg) = recvmsg {self.handle_logic(actmsg).await ;}}recvmsgchan= self.chanchan.recv()=>{if let Some(actmsg) = recvmsgchan {self.handle_logic2(actmsg).await ;}}_=tokio::time::sleep(Duration::from_millis(1000*8)) =>{}}} //end loop}

同步的方式的异步 go 很简单, rust go 上多一点点
go
在这里插入图片描述
rust
在这里插入图片描述

在这里插入图片描述

网络跟逻辑分开,这样 挤号,只需要把 logic future 里 sendclient mpsc 更新, 把网络 to logic mpsc 更新 及一些 状态重置下 即可,无需重新加载现有useractor 里的信息
类试单点登录 对于聊天服务器来说 ,只需要 角色进入后,由logic服 ase 对称加密(密钥及盐,logic 服 chat 服 共享/配置,共享方式自行决定)或 非对称(ECC) 等都可以,加密的token 由前端发送 给chat 服,chat 解密 得到 相应信息 并验证有效性 参考加解密验证用户的合法性

3:测试
前端简单用go 写了个

var origin = "http://192.168.1.32:8080"
var url = "wss://192.168.1.32:8080/websocket"
func GetProtoMsgID(data []byte) uint32 {var sMsgID uint16 = uint16(uint8(data[3] & 0x7f))if (uint8(data[3]) & 0x80) > 0 {sMsgID += (uint16(data[4]) & 0x7f) << 7}return uint32(sMsgID)
}func  sendMsg(ws *websocket.Conn,pb proto.Message) {if ws != nil {if data, err2 := proto.Marshal(pb); err2 != nil {log.Printf("SendMessage pb=%v err2=%v \n", pb, err2)} else {if err4 := websocket.Message.Send(ws, data); err4 != nil {log.Printf("send error =%v \n", err4)}}}
}func doLogicMsg(data []byte)  {msgId := GetProtoMsgID(data)fmt.Printf("msgid=%v",msgId)switch msgId {case uint32(chatproto.CHATMSG_CHC_Login_Rep):{loginReq := &chatproto.ChatMessageLoginRep{}if err := proto.Unmarshal(data, loginReq); err != nil {} else {fmt.Printf("CHATMSG_CHC_Login_Rep =%v \n",loginReq.Res)}}case uint32(chatproto.CHATMSG_CCH_Chat_Rep):{chatrep := &chatproto.ChatMessageChatRep{}if err := proto.Unmarshal(data, chatrep); err != nil {} else {fmt.Printf("CHATMSG_CCH_Chat_Rep =%v \n",chatrep.Res)}}case uint32(chatproto.CHATMSG_CHC_Notify_Chat):{chatmsg := &chatproto.ChatMessageNotifyChat{}if err := proto.Unmarshal(data, chatmsg); err != nil {} else {fmt.Printf("CHATMSG_CHC_Notify_Chat =%v fromuserid=%v text=%v \n",chatmsg.Chattype,chatmsg.Senderid,chatmsg.Strcontext)}}}}
func getTimestamp() uint32 {return  uint32(time.Now().UTC().Unix());
}func main(){//if os.Args[0]userid :=  getTimestamp()guildid := uint32(0)if len(os.Args) > 1 {if s,e := strconv.Atoi(os.Args[1]);e ==nil {userid = uint32(s)}}if len(os.Args) > 2 {if s,e := strconv.Atoi(os.Args[2]);e ==nil {guildid = uint32(s)}}ws, err := websocket.Dial(url, "", origin)if err != nil {log.Fatal(err)}fmt.Printf("userid=%v guild=%v \n",userid,guildid){msg := new(chatproto.ChatMessageLoginReq)msg.Msghead = &chatproto.ChatMessageHead{uint32(chatproto.CHATMSG_CCH_Login_Req), 1}msg.Userid = useridmsg.Username = "name_"+strconv.Itoa(int(userid))msg.Guildid = guildidmsg.Tokenmd5 = "md5"msg.Tokenstr = "Tokenstr"sendMsg(ws, msg)}disflag :=  false{go func() {for{buf := make([]byte, 1024*4)err := websocket.Message.Receive(ws, &buf)if err != nil {//log.Printf("websocket.Message.Receive err=%v  ---%s\n", err,self.getAccName())disflag = truereturn}if len(buf) >= 4 {doLogicMsg(buf)//self.msgQue.PostUserMessage(&ReceiveNetMsg{buf})} else {log.Printf("[error]recv data=%v \n", buf)return}}}()}time.Sleep(time.Second*3)//pub enum  ChatChannel{//	ChatChannel_NONE=0,//	ChatChannel_NORMAL,//	ChatChannel_GUILD,//	ChatChannel_WORLD,//	ChatChannel_ALL,//}{sendcount := uint32(1)num := uint32(0)msg := new(chatproto.ChatMessageChatReq)msg.Msghead = &chatproto.ChatMessageHead{uint32(chatproto.CHATMSG_CCH_Chat_Req), 1}msg.Chattype = 1msg.Context ="normal chat "+ strconv.Itoa(int(num))for {if disflag { //脏数据break}sendMsg(ws, msg)time.Sleep(time.Second*10)num++m := num % 3 +1msg.Chattype = uint32(m)msg.Context ="normal chat "+ strconv.Itoa(int(sendcount))fmt.Printf("[%v][%v] send chattype=%v \n",sendcount,getTimestamp(),msg.Chattype)sendcount++//if m == 3  {//	time.Sleep(time.Second*10)//}}}ws.Close()//关闭连接fmt.Printf("client exit\n")
}

相互挤号测试
在这里插入图片描述
4:DEMO工程 后续完善了如有需要再上传(当前只能说基本上跑起来)
如果觉得有用,麻烦点个赞,加个收藏

这篇关于rust学习基于tokio_actor聊天服务器实战(一 )的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/666670

相关文章

Java学习手册之Filter和Listener使用方法

《Java学习手册之Filter和Listener使用方法》:本文主要介绍Java学习手册之Filter和Listener使用方法的相关资料,Filter是一种拦截器,可以在请求到达Servl... 目录一、Filter(过滤器)1. Filter 的工作原理2. Filter 的配置与使用二、Listen

Go语言开发实现查询IP信息的MCP服务器

《Go语言开发实现查询IP信息的MCP服务器》随着MCP的快速普及和广泛应用,MCP服务器也层出不穷,本文将详细介绍如何在Go语言中使用go-mcp库来开发一个查询IP信息的MCP... 目录前言mcp-ip-geo 服务器目录结构说明查询 IP 信息功能实现工具实现工具管理查询单个 IP 信息工具的实现服

springboot上传zip包并解压至服务器nginx目录方式

《springboot上传zip包并解压至服务器nginx目录方式》:本文主要介绍springboot上传zip包并解压至服务器nginx目录方式,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录springboot上传zip包并解压至服务器nginx目录1.首先需要引入zip相关jar包2.然

将Java项目提交到云服务器的流程步骤

《将Java项目提交到云服务器的流程步骤》所谓将项目提交到云服务器即将你的项目打成一个jar包然后提交到云服务器即可,因此我们需要准备服务器环境为:Linux+JDK+MariDB(MySQL)+Gi... 目录1. 安装 jdk1.1 查看 jdk 版本1.2 下载 jdk2. 安装 mariadb(my

Python列表去重的4种核心方法与实战指南详解

《Python列表去重的4种核心方法与实战指南详解》在Python开发中,处理列表数据时经常需要去除重复元素,本文将详细介绍4种最实用的列表去重方法,有需要的小伙伴可以根据自己的需要进行选择... 目录方法1:集合(set)去重法(最快速)方法2:顺序遍历法(保持顺序)方法3:副本删除法(原地修改)方法4:

在Spring Boot中浅尝内存泄漏的实战记录

《在SpringBoot中浅尝内存泄漏的实战记录》本文给大家分享在SpringBoot中浅尝内存泄漏的实战记录,结合实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录使用静态集合持有对象引用,阻止GC回收关键点:可执行代码:验证:1,运行程序(启动时添加JVM参数限制堆大小):2,访问 htt

Spring Security基于数据库的ABAC属性权限模型实战开发教程

《SpringSecurity基于数据库的ABAC属性权限模型实战开发教程》:本文主要介绍SpringSecurity基于数据库的ABAC属性权限模型实战开发教程,本文给大家介绍的非常详细,对大... 目录1. 前言2. 权限决策依据RBACABAC综合对比3. 数据库表结构说明4. 实战开始5. MyBA

基于Python打造一个可视化FTP服务器

《基于Python打造一个可视化FTP服务器》在日常办公和团队协作中,文件共享是一个不可或缺的需求,所以本文将使用Python+Tkinter+pyftpdlib开发一款可视化FTP服务器,有需要的小... 目录1. 概述2. 功能介绍3. 如何使用4. 代码解析5. 运行效果6.相关源码7. 总结与展望1

使用Python开发一个简单的本地图片服务器

《使用Python开发一个简单的本地图片服务器》本文介绍了如何结合wxPython构建的图形用户界面GUI和Python内建的Web服务器功能,在本地网络中搭建一个私人的,即开即用的网页相册,文中的示... 目录项目目标核心技术栈代码深度解析完整代码工作流程主要功能与优势潜在改进与思考运行结果总结你是否曾经

使用Python实现快速搭建本地HTTP服务器

《使用Python实现快速搭建本地HTTP服务器》:本文主要介绍如何使用Python快速搭建本地HTTP服务器,轻松实现一键HTTP文件共享,同时结合二维码技术,让访问更简单,感兴趣的小伙伴可以了... 目录1. 概述2. 快速搭建 HTTP 文件共享服务2.1 核心思路2.2 代码实现2.3 代码解读3.