# rpc-rs **Repository Path**: ldh123/rpc-rs ## Basic Information - **Project Name**: rpc-rs - **Description**: IM服务端-rust实现 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-04-01 - **Last Updated**: 2026-04-10 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## Rust Rpc 设计思想 rpc基于tokio实现的, 能够完成socket, websocket, udp三种通信模式。 整个设计思想基于http,编写 socket和编写http一样简单。 ### 主要组件如下: RpcConnection: 通信基础组件。 RpcContext: 通信基础组件的辅助组件。 RpcChannel: 输入管道流。 RpcConnectionManager: 通信连接管理器,消息转发,重试等 RpcRouter: Router组件,提供接口服务入口,相当于spring mvc中的Controller组件 Service: 客户接口,和router配套,调佣service能够和router进行通信。 RpdEvent: 事件接口 RpcFilter: 过滤器,对请求进行拦截,能够完成权限控制等功能 RpcCodec: 编码接口, 默认支持json和bincode二进制编码两种模式,实现此接口,能够完成其他编码格式 RpcSession: 连接会话,可以存储会话信息 #### 服务端用例: ``` let _ = RpcServerBuilder::new(8888) .router("/hello", router!(hello)) .set_current_codec_type("json") .set_local_seq_creator(DefaultLocalSeqCreator::new("server-demo".to_string())) .build().start_server().await; ``` 编写Router,提供服务接口: ``` #[rpc_router] fn hello(context: &mut dyn RpcContext, data: i32, value: String) -> i32 { context.send_event(Box::new(HelloEvent {})).unwrap(); data + 100 } ``` 事件接口: ``` struct HelloEvent {} impl RpcEvent for HelloEvent { fn consume(&self) -> RpcResult<()> { log::info!("received hello message"); Ok(()) } } ``` #### 客户端用例: ``` let (context, mut channel) = RpcClientBuilder::new(&format!("localhost:{}", port)) .set_current_codec_type(codec_type) .set_local_seq_creator(DefaultLocalSeqCreator::new("demo".to_string())) .build().connection().await?; let mut hello_service = sender!(context, HelloService); for i in 0..100 { let result = hello_service.hello(&mut channel, i, "hello".to_string()).await?; log::info!("call result: {}", result); assert_eq!(result, i+100); } ``` 编写Service ``` #[rpc_sender] #[async_trait::async_trait] trait HelloService { #[path = "/hello"] async fn hello(&mut self, channel: &mut impl RpcChannel, value: i32, data: String) -> RpcResult; } ``` 运行测试用例,并有输出: cargo test --release -- --show-output expand 命令用法: C:/Users/37835/.cargo/bin/cargo.exe expand --bin socket_server --color always --theme Dracula --tests