├── ssmp-example ├── moon.pkg.json ├── moon.mod.json └── main │ ├── main.mbt │ ├── client.mbt │ └── server.mbt ├── ssmp ├── moon.mod.json ├── moon.pkg.json └── lib │ └── ssmp.mbt ├── README.md └── LICENSE /ssmp-example/moon.pkg.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ssmp-example", 3 | "type": "executable" 4 | } -------------------------------------------------------------------------------- /ssmp-example/moon.mod.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ssmp-example", 3 | "version":"0.1.0", 4 | "deps" : [ 5 | "nodex/ssmp" 6 | ] 7 | } -------------------------------------------------------------------------------- /ssmp/moon.mod.json: -------------------------------------------------------------------------------- 1 | { 2 | "name":"nodex/ssmp", 3 | "version":"0.1.1", 4 | "deps":[], 5 | "readme":"README.md", 6 | "repository":"https://github.com/node/ssmp-moonbit", 7 | "license":"Apache-2.0", 8 | "keyword":["ssmp","protocol","network"] 9 | } 10 | -------------------------------------------------------------------------------- /ssmp/moon.pkg.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ssmp", 3 | "type": "library", 4 | "description": "A MoonBit implementation of the Simple Simple Messaging Protocol (SSMP) for handling length-prefixed message streams.", 5 | "keywords": [ 6 | "ssmp", 7 | "protocol", 8 | "tcp", 9 | "network", 10 | "parser" 11 | ], 12 | "license": "Apache-2.0" 13 | } -------------------------------------------------------------------------------- /ssmp-example/main/main.mbt: -------------------------------------------------------------------------------- 1 | // main 2 | fn main { 3 | let addr = "127.0.0.1:8088" 4 | let num_clients = 3 // 在这里设置要启动的客户端数量 5 | 6 | // 1. 在后台任务中启动服务器 7 | spawn server::start(addr) 8 | 9 | // 2. 短暂等待,确保服务器已开始监听 10 | os::sleep(1.0) 11 | 12 | // 3. 准备并启动多个客户端 13 | println("[Main] Starting \(num_clients) clients...") 14 | let wg = WaitGroup::new() 15 | for i = 0..num_clients { 16 | wg.add(1) // 为即将启动的客户端任务增加计数 17 | // `wg.clone()` 是必要的,因为它会被移动到新的任务中 18 | spawn client::start(i, addr, wg.clone()) 19 | } 20 | 21 | // 4. 等待所有客户端任务完成 22 | // `wg.wait()` 会阻塞当前任务,直到WaitGroup的计数器降为0 23 | wg.wait() 24 | 25 | println("[Main] All client tasks have completed. Exiting.") 26 | // 主程序在这里结束 27 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ssmp-moonbit 2 | SSMP implementation in MoonBit 3 | 4 | *WARNING:* THIS IS AN EXPERIMENTAL LIBRARY, PLEASE DO NOT USE IT IN YOUR PRODUCTION DIRECTLY. 5 | 6 | 这是一个使用 [MoonBit 语言](https://www.moonbitlang.com/) 实现的 [SSMP (Simple Simple Messaging Protocol) ](https://github.com/node/ssmp) 协议库及示例程序。 7 | 8 | 本项目包含一个健壮的协议库,用于序列化和反序列化 SSMP 消息,以及一个演示其用法的高性能 TCP 客户端/服务器应用。 9 | 10 | ## ✨ 功能特性 11 | ### 协议库 (lib/ssmp.mbt): 12 | 13 | 提供一个 serialize 函数,可将任意字节载荷(Bytes)打包成符合 SSMP 规范的消息。 14 | 15 | 提供一个带状态的 Parser 结构体,能够处理任意大小和分片的 TCP 数据流,并准确解析出完整的 SSMP 消息。 16 | 17 | ### 并发 TCP 服务器 (main/server.mbt): 18 | 19 | 一个多任务 TCP 服务器,为每一个客户端连接创建一个独立的协程(task)进行处理。 20 | 21 | 能够同时高效地处理多个客户端的并发请求。 22 | 23 | ### 并发 TCP 客户端 (main/client.mbt): 24 | 25 | 一个可以实例化多个的客户端模块。 26 | 27 | 主程序 (main/main.mbt) 演示了如何并发启动多个客户端实例,以测试服务器的并发处理能力。 28 | 29 | 30 | ## 📁 项目结构 31 | ``` 32 | ssmp-moonbit/ 33 | ├── LICENSE 34 | ├── README.md 35 | ├── ssmp 36 | ├── lib/ 37 | │ └── ssmp.mbt # SSMP 协议库核心实现 38 | ├── moon.mod.json # 项目模块定义 39 | ├── moon.pkg.json # 项目包定义 40 | ├── ssmp-example 41 | └── main/ 42 | ├── main.mbt # 主程序入口,负责启动服务器和客户端 43 | ├── server.mbt # TCP 服务器逻辑 44 | └── client.mbt # TCP 客户端逻辑 45 | ├── moon.mod.json 46 | ├── moon.pkg.json 47 | ``` 48 | 49 | ## 🚀 开始使用 50 | 51 | **前提准备** 52 | 53 | 您需要先安装 MoonBit 开发工具链。请参照 [MoonBit 官方网站](https://www.moonbitlang.com/) 的指引进行安装。 54 | 55 | ### 运行 Demo 56 | 57 | 将本项目克隆或下载到本地后,在项目根目录 ssmp-moonbit/ 下打开终端,执行以下命令: 58 | 59 | ``` Bash 60 | moon run 61 | ``` 62 | 63 | 程序将会启动一个服务器,然后启动3个客户端并发地向服务器发送消息并接收回复。整个过程在几秒钟内完成。 64 | 65 | ### 更多尝试 66 | 67 | 您可以基于此项目,开发满足你自己个性化需求的基于SSMP协议的网络应用程序,比如一个简单的物联网数据采集服务、一个手机WiFi热点信息收集服务等。 68 | 69 | -------------------------------------------------------------------------------- /ssmp-example/main/client.mbt: -------------------------------------------------------------------------------- 1 | //use moonbit/tcp::TcpStream 2 | //use moonbit/io::{Reader, Writer, close} 3 | //use moonbit/sync::WaitGroup 4 | //use core::result::{Result, Ok, Err} 5 | 6 | /// 启动一个客户端实例 7 | pub fn start(id: Int, addr: String, wg: WaitGroup) { 8 | // `finally` 确保无论函数如何退出(正常结束或出错),`wg.done()` 都会被调用 9 | finally { 10 | wg.done() 11 | } 12 | 13 | println("[Client \(id)] Connecting to \(addr)...") 14 | match TcpStream::connect(addr) { 15 | Ok(mut stream) => { 16 | println("[Client \(id)] Connected.") 17 | 18 | let messages_to_send = [ 19 | "message 1 from client \(id)", 20 | "message 2 from client \(id)", 21 | ] 22 | 23 | for msg_str in messages_to_send.iter() { 24 | let packet = ssmp::serialize(msg_str.to_bytes()) 25 | stream.write(packet).unwrap() 26 | println("[Client \(id)] Sent: '\(msg_str)'") 27 | os::sleep(0.2) // 短暂休眠,让输出不至于完全混乱 28 | } 29 | 30 | let mut parser = ssmp::Parser::new() 31 | let mut read_buf = Bytes::make(1024) 32 | let mut replies_received = 0 33 | let total_replies_expected = messages_to_send.length() 34 | 35 | // 设置一个简单的超时逻辑 36 | for _ = 0..10 { // 最多尝试读取10次 37 | if replies_received >= total_replies_expected { break } 38 | 39 | match stream.read(read_buf) { 40 | Ok(0) => break, 41 | Ok(n) => { 42 | let replies = parser.feed(read_buf.slice(0, n)) 43 | for reply in replies.iter() { 44 | println("[Client \(id)] Received: '\(reply.to_string_lossy())'") 45 | replies_received += 1 46 | } 47 | } 48 | Err(_) => break 49 | } 50 | os::sleep(0.2) 51 | } 52 | println("[Client \(id)] Finished.") 53 | close(stream).unwrap() 54 | } 55 | Err(e) => { 56 | println("[Client \(id)] Failed to connect: \(e.to_string())") 57 | } 58 | } 59 | } -------------------------------------------------------------------------------- /ssmp-example/main/server.mbt: -------------------------------------------------------------------------------- 1 | //use moonbit/tcp::{TcpListener, TcpStream} 2 | //use moonbit/io::{Reader, Writer, close} 3 | //use core::result::{Result, Ok, Err} 4 | //use core::string::String 5 | 6 | // 处理单个客户端连接的函数 7 | fn handle_connection(mut stream: TcpStream) -> Result[Unit, String] { 8 | println("[Server] New connection received.") 9 | let mut parser = ssmp::Parser::new() 10 | let mut read_buf = Bytes::make(1024) 11 | 12 | loop { 13 | match stream.read(read_buf) { 14 | Ok(0) => { 15 | println("[Server] Connection closed by a client.") 16 | break 17 | } 18 | Ok(n) => { 19 | let data = read_buf.slice(0, n) 20 | let messages = parser.feed(data) 21 | 22 | for msg in messages.iter() { 23 | let content = msg.to_string_lossy() 24 | println("[Server] Parsed message: '\(content)'") 25 | 26 | let reply_payload = "Server ACK for: \(content)".to_bytes() 27 | let reply_packet = ssmp::serialize(reply_payload) 28 | stream.write(reply_packet)? 29 | println("[Server] Sent reply.") 30 | } 31 | } 32 | Err(e) => { 33 | println("[Server] Read error: \(e.to_string())") 34 | break 35 | } 36 | } 37 | } 38 | 39 | close(stream) 40 | Ok(()) 41 | } 42 | 43 | /// 启动 TCP 服务器并开始监听连接 44 | pub fn start(addr: String) { 45 | println("[Server] Starting on \(addr)...") 46 | match TcpListener::bind(addr) { 47 | Ok(listener) => { 48 | loop { 49 | match listener.accept() { 50 | Ok((stream, _)) => { 51 | // 为每个新连接创建一个独立的任务 52 | spawn handle_connection(stream) 53 | } 54 | Err(e) => { 55 | println("[Server] Accept error: \(e.to_string())") 56 | break 57 | } 58 | } 59 | } 60 | } 61 | Err(e) => { 62 | println("[Server] Failed to bind address: \(e.to_string())") 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /ssmp/lib/ssmp.mbt: -------------------------------------------------------------------------------- 1 | /// SSMP 协议解析器,用于处理流式数据。 2 | /// 3 | /// 它可以接收任意大小的数据块,并在内部缓冲, 4 | /// 当一个或多个完整的SSMP消息被解析出来时,将它们返回。 5 | /// 6 | /// # Example 7 | /// ``` 8 | /// let mut parser = ssmp::Parser::new() 9 | /// // 模拟接收到的网络数据 10 | /// let chunk1 = ssmp::serialize("hello".to_bytes()) 11 | /// let chunk2 = ssmp::serialize("world".to_bytes()) 12 | /// let messages = parser.feed(Bytes::concat(chunk1, chunk2)) 13 | /// assert(messages.length() == 2) 14 | /// ``` 15 | pub struct Parser { 16 | mut buffer: Buffer 17 | mut state: State 18 | } 19 | 20 | // ...(内部 `enum State` 定义保持不变)... 21 | 22 | impl Parser { 23 | /// 创建一个新的、状态为空的解析器实例。 24 | pub fn new() -> Self { 25 | { 26 | buffer: Buffer::new(), 27 | state: State::ReadingLen, 28 | } 29 | } 30 | 31 | /// 向解析器提供新的数据块 (`data`),并尝试解析出零个或多个完整的消息。 32 | /// 33 | /// ## Parameters 34 | /// - `data`: 从网络流中读取到的原始字节数据。 35 | /// 36 | /// ## Returns 37 | /// 一个包含所有已成功解析出的消息载荷(`Bytes`)的数组。 38 | /// 如果没有解析出完整的消息,则返回空数组。 39 | pub fn feed(&mut self, data: Bytes) -> Array[Bytes] { 40 | // ... (函数实现保持不变) ... 41 | self.buffer.write_bytes(data) 42 | 43 | let mut messages = Array::new() 44 | loop { 45 | match self.state { 46 | State::ReadingLen => { 47 | if self.buffer.readable_bytes() >= 4 { 48 | let body_len = self.buffer.read_u32_be().unwrap() 49 | self.state = State::ReadingBody(body_len) 50 | } else { 51 | break 52 | } 53 | } 54 | State::ReadingBody(body_len) => { 55 | if self.buffer.readable_bytes() >= (body_len as Int) { 56 | let payload = self.buffer.read_bytes(body_len as Int).unwrap() 57 | messages.push(payload) 58 | self.state = State::ReadingLen 59 | } else { 60 | break 61 | } 62 | } 63 | } 64 | } 65 | messages 66 | } 67 | } 68 | 69 | /// 将载荷(`Bytes`)序列化为一个完整的 SSMP 消息包(头部 + 载荷)。 70 | /// 71 | /// ## Parameters 72 | /// - `payload`: 需要被打包发送的原始字节数据。 73 | /// 74 | /// ## Returns 75 | /// 一个包含了4字节大端序长度前缀和载荷的完整 SSMP 消息包。 76 | pub fn serialize(payload: Bytes) -> Bytes { 77 | // ... (函数实现保持不变) ... 78 | let len = payload.length() 79 | let mut buf = Buffer::with_capacity(4 + len) 80 | buf.write_u32_be(len as U32) 81 | buf.write_bytes(payload) 82 | buf.to_bytes() 83 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------