├── .github ├── dependabot.yml └── workflows │ └── maven.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── pom.xml ├── protocol-zh.md ├── src ├── easechat-client-j │ ├── build.gradle.kts │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── net │ │ └── easecation │ │ └── easechat │ │ ├── Main.java │ │ ├── api │ │ ├── Logger.java │ │ ├── Message.java │ │ ├── MessageReceiver.java │ │ ├── MessageSender.java │ │ ├── SimpleLogger.java │ │ └── message │ │ │ ├── AutoSubChannelMessage.java │ │ │ ├── ChannelMessage.java │ │ │ ├── DisconnectMessage.java │ │ │ ├── HelloMessage.java │ │ │ ├── ReceiveMessage.java │ │ │ └── TransmitMessage.java │ │ └── network │ │ ├── EaseChatClient.java │ │ ├── MessageCodec.java │ │ └── MessageHandler.java ├── easechat-exec-rs │ ├── Cargo.toml │ └── src │ │ └── main.rs ├── easechat-nexus-rs │ ├── Cargo.toml │ ├── examples │ │ └── console_parser.rs │ └── src │ │ ├── console_rule.pest │ │ └── main.rs ├── easechat-nexus-v2-rs │ ├── Cargo.toml │ └── src │ │ ├── adapt.rs │ │ ├── lib.rs │ │ └── service.rs └── easechat-record-rs │ ├── Cargo.toml │ ├── examples │ └── simple-mem-db.rs │ └── src │ └── main.rs └── start.bat /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "maven" 4 | directory: "/" 5 | schedule: 6 | interval: "monthly" 7 | -------------------------------------------------------------------------------- /.github/workflows/maven.yml: -------------------------------------------------------------------------------- 1 | name: Java CI 2 | 3 | on: 4 | push: 5 | workflow_dispatch: 6 | 7 | jobs: 8 | build: 9 | name: Java ${{ matrix.java }} 10 | runs-on: ubuntu-latest 11 | strategy: 12 | fail-fast: false 13 | matrix: 14 | java: 15 | [ 16 | 21, 17 | ] 18 | steps: 19 | - name: Checkout 20 | uses: actions/checkout@v4 21 | - name: Set up JDK ${{ matrix.java }} 22 | uses: actions/setup-java@v4 23 | with: 24 | java-version: ${{ matrix.java }} 25 | distribution: oracle 26 | cache: maven 27 | - name: Build with Maven 28 | run: mvn -B clean package 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **/target 2 | **/*.rs.bk 3 | .idea/ 4 | _server/ 5 | **/*.iml 6 | **/*.class 7 | **/*.jar 8 | tstart.sh 9 | build 10 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "android_system_properties" 7 | version = "0.1.5" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" 10 | dependencies = [ 11 | "libc", 12 | ] 13 | 14 | [[package]] 15 | name = "ansi_term" 16 | version = "0.12.1" 17 | source = "registry+https://github.com/rust-lang/crates.io-index" 18 | checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2" 19 | dependencies = [ 20 | "winapi 0.3.9", 21 | ] 22 | 23 | [[package]] 24 | name = "atty" 25 | version = "0.2.14" 26 | source = "registry+https://github.com/rust-lang/crates.io-index" 27 | checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" 28 | dependencies = [ 29 | "hermit-abi", 30 | "libc", 31 | "winapi 0.3.9", 32 | ] 33 | 34 | [[package]] 35 | name = "autocfg" 36 | version = "1.1.0" 37 | source = "registry+https://github.com/rust-lang/crates.io-index" 38 | checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" 39 | 40 | [[package]] 41 | name = "bitflags" 42 | version = "1.3.2" 43 | source = "registry+https://github.com/rust-lang/crates.io-index" 44 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" 45 | 46 | [[package]] 47 | name = "block-buffer" 48 | version = "0.10.3" 49 | source = "registry+https://github.com/rust-lang/crates.io-index" 50 | checksum = "69cce20737498f97b993470a6e536b8523f0af7892a4f928cceb1ac5e52ebe7e" 51 | dependencies = [ 52 | "generic-array", 53 | ] 54 | 55 | [[package]] 56 | name = "bumpalo" 57 | version = "3.11.1" 58 | source = "registry+https://github.com/rust-lang/crates.io-index" 59 | checksum = "572f695136211188308f16ad2ca5c851a712c464060ae6974944458eb83880ba" 60 | 61 | [[package]] 62 | name = "byteorder" 63 | version = "1.4.3" 64 | source = "registry+https://github.com/rust-lang/crates.io-index" 65 | checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" 66 | 67 | [[package]] 68 | name = "bytes" 69 | version = "0.4.12" 70 | source = "registry+https://github.com/rust-lang/crates.io-index" 71 | checksum = "206fdffcfa2df7cbe15601ef46c813fce0965eb3286db6b56c583b814b51c81c" 72 | dependencies = [ 73 | "byteorder", 74 | "iovec", 75 | ] 76 | 77 | [[package]] 78 | name = "cc" 79 | version = "1.0.77" 80 | source = "registry+https://github.com/rust-lang/crates.io-index" 81 | checksum = "e9f73505338f7d905b19d18738976aae232eb46b8efc15554ffc56deb5d9ebe4" 82 | 83 | [[package]] 84 | name = "cfg-if" 85 | version = "0.1.10" 86 | source = "registry+https://github.com/rust-lang/crates.io-index" 87 | checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" 88 | 89 | [[package]] 90 | name = "cfg-if" 91 | version = "1.0.0" 92 | source = "registry+https://github.com/rust-lang/crates.io-index" 93 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 94 | 95 | [[package]] 96 | name = "chrono" 97 | version = "0.4.23" 98 | source = "registry+https://github.com/rust-lang/crates.io-index" 99 | checksum = "16b0a3d9ed01224b22057780a37bb8c5dbfe1be8ba48678e7bf57ec4b385411f" 100 | dependencies = [ 101 | "iana-time-zone", 102 | "js-sys", 103 | "num-integer", 104 | "num-traits", 105 | "time", 106 | "wasm-bindgen", 107 | "winapi 0.3.9", 108 | ] 109 | 110 | [[package]] 111 | name = "clap" 112 | version = "2.34.0" 113 | source = "registry+https://github.com/rust-lang/crates.io-index" 114 | checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" 115 | dependencies = [ 116 | "ansi_term", 117 | "atty", 118 | "bitflags", 119 | "strsim", 120 | "textwrap", 121 | "unicode-width", 122 | "vec_map", 123 | ] 124 | 125 | [[package]] 126 | name = "codespan-reporting" 127 | version = "0.11.1" 128 | source = "registry+https://github.com/rust-lang/crates.io-index" 129 | checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" 130 | dependencies = [ 131 | "termcolor", 132 | "unicode-width", 133 | ] 134 | 135 | [[package]] 136 | name = "core-foundation-sys" 137 | version = "0.8.3" 138 | source = "registry+https://github.com/rust-lang/crates.io-index" 139 | checksum = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc" 140 | 141 | [[package]] 142 | name = "cpufeatures" 143 | version = "0.2.5" 144 | source = "registry+https://github.com/rust-lang/crates.io-index" 145 | checksum = "28d997bd5e24a5928dd43e46dc529867e207907fe0b239c3477d924f7f2ca320" 146 | dependencies = [ 147 | "libc", 148 | ] 149 | 150 | [[package]] 151 | name = "crypto-common" 152 | version = "0.1.6" 153 | source = "registry+https://github.com/rust-lang/crates.io-index" 154 | checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" 155 | dependencies = [ 156 | "generic-array", 157 | "typenum", 158 | ] 159 | 160 | [[package]] 161 | name = "cxx" 162 | version = "1.0.83" 163 | source = "registry+https://github.com/rust-lang/crates.io-index" 164 | checksum = "bdf07d07d6531bfcdbe9b8b739b104610c6508dcc4d63b410585faf338241daf" 165 | dependencies = [ 166 | "cc", 167 | "cxxbridge-flags", 168 | "cxxbridge-macro", 169 | "link-cplusplus", 170 | ] 171 | 172 | [[package]] 173 | name = "cxx-build" 174 | version = "1.0.83" 175 | source = "registry+https://github.com/rust-lang/crates.io-index" 176 | checksum = "d2eb5b96ecdc99f72657332953d4d9c50135af1bac34277801cc3937906ebd39" 177 | dependencies = [ 178 | "cc", 179 | "codespan-reporting", 180 | "once_cell", 181 | "proc-macro2", 182 | "quote", 183 | "scratch", 184 | "syn", 185 | ] 186 | 187 | [[package]] 188 | name = "cxxbridge-flags" 189 | version = "1.0.83" 190 | source = "registry+https://github.com/rust-lang/crates.io-index" 191 | checksum = "ac040a39517fd1674e0f32177648334b0f4074625b5588a64519804ba0553b12" 192 | 193 | [[package]] 194 | name = "cxxbridge-macro" 195 | version = "1.0.83" 196 | source = "registry+https://github.com/rust-lang/crates.io-index" 197 | checksum = "1362b0ddcfc4eb0a1f57b68bd77dd99f0e826958a96abd0ae9bd092e114ffed6" 198 | dependencies = [ 199 | "proc-macro2", 200 | "quote", 201 | "syn", 202 | ] 203 | 204 | [[package]] 205 | name = "digest" 206 | version = "0.10.6" 207 | source = "registry+https://github.com/rust-lang/crates.io-index" 208 | checksum = "8168378f4e5023e7218c89c891c0fd8ecdb5e5e4f18cb78f38cf245dd021e76f" 209 | dependencies = [ 210 | "block-buffer", 211 | "crypto-common", 212 | ] 213 | 214 | [[package]] 215 | name = "ease_chat_nexus" 216 | version = "0.0.2" 217 | dependencies = [ 218 | "pest", 219 | "pest_derive", 220 | "ws", 221 | ] 222 | 223 | [[package]] 224 | name = "easechat-exec" 225 | version = "0.0.0" 226 | dependencies = [ 227 | "easechat-nexus", 228 | ] 229 | 230 | [[package]] 231 | name = "easechat-nexus" 232 | version = "0.0.0" 233 | dependencies = [ 234 | "ws", 235 | ] 236 | 237 | [[package]] 238 | name = "easechat-record" 239 | version = "0.0.0" 240 | dependencies = [ 241 | "chrono", 242 | "clap", 243 | "rusqlite", 244 | "ws", 245 | ] 246 | 247 | [[package]] 248 | name = "fuchsia-cprng" 249 | version = "0.1.1" 250 | source = "registry+https://github.com/rust-lang/crates.io-index" 251 | checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" 252 | 253 | [[package]] 254 | name = "fuchsia-zircon" 255 | version = "0.3.3" 256 | source = "registry+https://github.com/rust-lang/crates.io-index" 257 | checksum = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" 258 | dependencies = [ 259 | "bitflags", 260 | "fuchsia-zircon-sys", 261 | ] 262 | 263 | [[package]] 264 | name = "fuchsia-zircon-sys" 265 | version = "0.3.3" 266 | source = "registry+https://github.com/rust-lang/crates.io-index" 267 | checksum = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" 268 | 269 | [[package]] 270 | name = "generic-array" 271 | version = "0.14.6" 272 | source = "registry+https://github.com/rust-lang/crates.io-index" 273 | checksum = "bff49e947297f3312447abdca79f45f4738097cc82b06e72054d2223f601f1b9" 274 | dependencies = [ 275 | "typenum", 276 | "version_check", 277 | ] 278 | 279 | [[package]] 280 | name = "hermit-abi" 281 | version = "0.1.19" 282 | source = "registry+https://github.com/rust-lang/crates.io-index" 283 | checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" 284 | dependencies = [ 285 | "libc", 286 | ] 287 | 288 | [[package]] 289 | name = "httparse" 290 | version = "1.8.0" 291 | source = "registry+https://github.com/rust-lang/crates.io-index" 292 | checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" 293 | 294 | [[package]] 295 | name = "iana-time-zone" 296 | version = "0.1.53" 297 | source = "registry+https://github.com/rust-lang/crates.io-index" 298 | checksum = "64c122667b287044802d6ce17ee2ddf13207ed924c712de9a66a5814d5b64765" 299 | dependencies = [ 300 | "android_system_properties", 301 | "core-foundation-sys", 302 | "iana-time-zone-haiku", 303 | "js-sys", 304 | "wasm-bindgen", 305 | "winapi 0.3.9", 306 | ] 307 | 308 | [[package]] 309 | name = "iana-time-zone-haiku" 310 | version = "0.1.1" 311 | source = "registry+https://github.com/rust-lang/crates.io-index" 312 | checksum = "0703ae284fc167426161c2e3f1da3ea71d94b21bedbcc9494e92b28e334e3dca" 313 | dependencies = [ 314 | "cxx", 315 | "cxx-build", 316 | ] 317 | 318 | [[package]] 319 | name = "idna" 320 | version = "0.1.5" 321 | source = "registry+https://github.com/rust-lang/crates.io-index" 322 | checksum = "38f09e0f0b1fb55fdee1f17470ad800da77af5186a1a76c026b679358b7e844e" 323 | dependencies = [ 324 | "matches", 325 | "unicode-bidi", 326 | "unicode-normalization", 327 | ] 328 | 329 | [[package]] 330 | name = "iovec" 331 | version = "0.1.4" 332 | source = "registry+https://github.com/rust-lang/crates.io-index" 333 | checksum = "b2b3ea6ff95e175473f8ffe6a7eb7c00d054240321b84c57051175fe3c1e075e" 334 | dependencies = [ 335 | "libc", 336 | ] 337 | 338 | [[package]] 339 | name = "js-sys" 340 | version = "0.3.60" 341 | source = "registry+https://github.com/rust-lang/crates.io-index" 342 | checksum = "49409df3e3bf0856b916e2ceaca09ee28e6871cf7d9ce97a692cacfdb2a25a47" 343 | dependencies = [ 344 | "wasm-bindgen", 345 | ] 346 | 347 | [[package]] 348 | name = "kernel32-sys" 349 | version = "0.2.2" 350 | source = "registry+https://github.com/rust-lang/crates.io-index" 351 | checksum = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" 352 | dependencies = [ 353 | "winapi 0.2.8", 354 | "winapi-build", 355 | ] 356 | 357 | [[package]] 358 | name = "lazycell" 359 | version = "1.3.0" 360 | source = "registry+https://github.com/rust-lang/crates.io-index" 361 | checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" 362 | 363 | [[package]] 364 | name = "libc" 365 | version = "0.2.138" 366 | source = "registry+https://github.com/rust-lang/crates.io-index" 367 | checksum = "db6d7e329c562c5dfab7a46a2afabc8b987ab9a4834c9d1ca04dc54c1546cef8" 368 | 369 | [[package]] 370 | name = "libsqlite3-sys" 371 | version = "0.11.1" 372 | source = "registry+https://github.com/rust-lang/crates.io-index" 373 | checksum = "3567bc1a0c84e2c0d71eeb4a1f08451babf7843babd733158777d9c686dad9f3" 374 | dependencies = [ 375 | "pkg-config", 376 | "vcpkg", 377 | ] 378 | 379 | [[package]] 380 | name = "link-cplusplus" 381 | version = "1.0.7" 382 | source = "registry+https://github.com/rust-lang/crates.io-index" 383 | checksum = "9272ab7b96c9046fbc5bc56c06c117cb639fe2d509df0c421cad82d2915cf369" 384 | dependencies = [ 385 | "cc", 386 | ] 387 | 388 | [[package]] 389 | name = "linked-hash-map" 390 | version = "0.5.6" 391 | source = "registry+https://github.com/rust-lang/crates.io-index" 392 | checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" 393 | 394 | [[package]] 395 | name = "log" 396 | version = "0.4.17" 397 | source = "registry+https://github.com/rust-lang/crates.io-index" 398 | checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" 399 | dependencies = [ 400 | "cfg-if 1.0.0", 401 | ] 402 | 403 | [[package]] 404 | name = "lru-cache" 405 | version = "0.1.2" 406 | source = "registry+https://github.com/rust-lang/crates.io-index" 407 | checksum = "31e24f1ad8321ca0e8a1e0ac13f23cb668e6f5466c2c57319f6a5cf1cc8e3b1c" 408 | dependencies = [ 409 | "linked-hash-map", 410 | ] 411 | 412 | [[package]] 413 | name = "matches" 414 | version = "0.1.9" 415 | source = "registry+https://github.com/rust-lang/crates.io-index" 416 | checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" 417 | 418 | [[package]] 419 | name = "mio" 420 | version = "0.6.23" 421 | source = "registry+https://github.com/rust-lang/crates.io-index" 422 | checksum = "4afd66f5b91bf2a3bc13fad0e21caedac168ca4c707504e75585648ae80e4cc4" 423 | dependencies = [ 424 | "cfg-if 0.1.10", 425 | "fuchsia-zircon", 426 | "fuchsia-zircon-sys", 427 | "iovec", 428 | "kernel32-sys", 429 | "libc", 430 | "log", 431 | "miow", 432 | "net2", 433 | "slab", 434 | "winapi 0.2.8", 435 | ] 436 | 437 | [[package]] 438 | name = "mio-extras" 439 | version = "2.0.6" 440 | source = "registry+https://github.com/rust-lang/crates.io-index" 441 | checksum = "52403fe290012ce777c4626790c8951324a2b9e3316b3143779c72b029742f19" 442 | dependencies = [ 443 | "lazycell", 444 | "log", 445 | "mio", 446 | "slab", 447 | ] 448 | 449 | [[package]] 450 | name = "miow" 451 | version = "0.2.2" 452 | source = "registry+https://github.com/rust-lang/crates.io-index" 453 | checksum = "ebd808424166322d4a38da87083bfddd3ac4c131334ed55856112eb06d46944d" 454 | dependencies = [ 455 | "kernel32-sys", 456 | "net2", 457 | "winapi 0.2.8", 458 | "ws2_32-sys", 459 | ] 460 | 461 | [[package]] 462 | name = "net2" 463 | version = "0.2.38" 464 | source = "registry+https://github.com/rust-lang/crates.io-index" 465 | checksum = "74d0df99cfcd2530b2e694f6e17e7f37b8e26bb23983ac530c0c97408837c631" 466 | dependencies = [ 467 | "cfg-if 0.1.10", 468 | "libc", 469 | "winapi 0.3.9", 470 | ] 471 | 472 | [[package]] 473 | name = "num-integer" 474 | version = "0.1.45" 475 | source = "registry+https://github.com/rust-lang/crates.io-index" 476 | checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" 477 | dependencies = [ 478 | "autocfg", 479 | "num-traits", 480 | ] 481 | 482 | [[package]] 483 | name = "num-traits" 484 | version = "0.2.15" 485 | source = "registry+https://github.com/rust-lang/crates.io-index" 486 | checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" 487 | dependencies = [ 488 | "autocfg", 489 | ] 490 | 491 | [[package]] 492 | name = "once_cell" 493 | version = "1.16.0" 494 | source = "registry+https://github.com/rust-lang/crates.io-index" 495 | checksum = "86f0b0d4bf799edbc74508c1e8bf170ff5f41238e5f8225603ca7caaae2b7860" 496 | 497 | [[package]] 498 | name = "percent-encoding" 499 | version = "1.0.1" 500 | source = "registry+https://github.com/rust-lang/crates.io-index" 501 | checksum = "31010dd2e1ac33d5b46a5b413495239882813e0369f8ed8a5e266f173602f831" 502 | 503 | [[package]] 504 | name = "pest" 505 | version = "2.5.1" 506 | source = "registry+https://github.com/rust-lang/crates.io-index" 507 | checksum = "cc8bed3549e0f9b0a2a78bf7c0018237a2cdf085eecbbc048e52612438e4e9d0" 508 | dependencies = [ 509 | "thiserror", 510 | "ucd-trie", 511 | ] 512 | 513 | [[package]] 514 | name = "pest_derive" 515 | version = "2.5.1" 516 | source = "registry+https://github.com/rust-lang/crates.io-index" 517 | checksum = "cdc078600d06ff90d4ed238f0119d84ab5d43dbaad278b0e33a8820293b32344" 518 | dependencies = [ 519 | "pest", 520 | "pest_generator", 521 | ] 522 | 523 | [[package]] 524 | name = "pest_generator" 525 | version = "2.5.1" 526 | source = "registry+https://github.com/rust-lang/crates.io-index" 527 | checksum = "28a1af60b1c4148bb269006a750cff8e2ea36aff34d2d96cf7be0b14d1bed23c" 528 | dependencies = [ 529 | "pest", 530 | "pest_meta", 531 | "proc-macro2", 532 | "quote", 533 | "syn", 534 | ] 535 | 536 | [[package]] 537 | name = "pest_meta" 538 | version = "2.5.1" 539 | source = "registry+https://github.com/rust-lang/crates.io-index" 540 | checksum = "fec8605d59fc2ae0c6c1aefc0c7c7a9769732017c0ce07f7a9cfffa7b4404f20" 541 | dependencies = [ 542 | "once_cell", 543 | "pest", 544 | "sha1 0.10.5", 545 | ] 546 | 547 | [[package]] 548 | name = "pkg-config" 549 | version = "0.3.26" 550 | source = "registry+https://github.com/rust-lang/crates.io-index" 551 | checksum = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160" 552 | 553 | [[package]] 554 | name = "proc-macro2" 555 | version = "1.0.47" 556 | source = "registry+https://github.com/rust-lang/crates.io-index" 557 | checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" 558 | dependencies = [ 559 | "unicode-ident", 560 | ] 561 | 562 | [[package]] 563 | name = "quote" 564 | version = "1.0.21" 565 | source = "registry+https://github.com/rust-lang/crates.io-index" 566 | checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" 567 | dependencies = [ 568 | "proc-macro2", 569 | ] 570 | 571 | [[package]] 572 | name = "rand" 573 | version = "0.4.6" 574 | source = "registry+https://github.com/rust-lang/crates.io-index" 575 | checksum = "552840b97013b1a26992c11eac34bdd778e464601a4c2054b5f0bff7c6761293" 576 | dependencies = [ 577 | "fuchsia-cprng", 578 | "libc", 579 | "rand_core 0.3.1", 580 | "rdrand", 581 | "winapi 0.3.9", 582 | ] 583 | 584 | [[package]] 585 | name = "rand_core" 586 | version = "0.3.1" 587 | source = "registry+https://github.com/rust-lang/crates.io-index" 588 | checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" 589 | dependencies = [ 590 | "rand_core 0.4.2", 591 | ] 592 | 593 | [[package]] 594 | name = "rand_core" 595 | version = "0.4.2" 596 | source = "registry+https://github.com/rust-lang/crates.io-index" 597 | checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" 598 | 599 | [[package]] 600 | name = "rdrand" 601 | version = "0.4.0" 602 | source = "registry+https://github.com/rust-lang/crates.io-index" 603 | checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" 604 | dependencies = [ 605 | "rand_core 0.3.1", 606 | ] 607 | 608 | [[package]] 609 | name = "rusqlite" 610 | version = "0.16.0" 611 | source = "registry+https://github.com/rust-lang/crates.io-index" 612 | checksum = "6381ddfe91dbb659b4b132168da15985bc84162378cf4fcdc4eb99c857d063e2" 613 | dependencies = [ 614 | "bitflags", 615 | "chrono", 616 | "libsqlite3-sys", 617 | "lru-cache", 618 | "time", 619 | ] 620 | 621 | [[package]] 622 | name = "scratch" 623 | version = "1.0.2" 624 | source = "registry+https://github.com/rust-lang/crates.io-index" 625 | checksum = "9c8132065adcfd6e02db789d9285a0deb2f3fcb04002865ab67d5fb103533898" 626 | 627 | [[package]] 628 | name = "sha1" 629 | version = "0.6.1" 630 | source = "registry+https://github.com/rust-lang/crates.io-index" 631 | checksum = "c1da05c97445caa12d05e848c4a4fcbbea29e748ac28f7e80e9b010392063770" 632 | dependencies = [ 633 | "sha1_smol", 634 | ] 635 | 636 | [[package]] 637 | name = "sha1" 638 | version = "0.10.5" 639 | source = "registry+https://github.com/rust-lang/crates.io-index" 640 | checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3" 641 | dependencies = [ 642 | "cfg-if 1.0.0", 643 | "cpufeatures", 644 | "digest", 645 | ] 646 | 647 | [[package]] 648 | name = "sha1_smol" 649 | version = "1.0.0" 650 | source = "registry+https://github.com/rust-lang/crates.io-index" 651 | checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012" 652 | 653 | [[package]] 654 | name = "slab" 655 | version = "0.4.7" 656 | source = "registry+https://github.com/rust-lang/crates.io-index" 657 | checksum = "4614a76b2a8be0058caa9dbbaf66d988527d86d003c11a94fbd335d7661edcef" 658 | dependencies = [ 659 | "autocfg", 660 | ] 661 | 662 | [[package]] 663 | name = "strsim" 664 | version = "0.8.0" 665 | source = "registry+https://github.com/rust-lang/crates.io-index" 666 | checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" 667 | 668 | [[package]] 669 | name = "syn" 670 | version = "1.0.105" 671 | source = "registry+https://github.com/rust-lang/crates.io-index" 672 | checksum = "60b9b43d45702de4c839cb9b51d9f529c5dd26a4aff255b42b1ebc03e88ee908" 673 | dependencies = [ 674 | "proc-macro2", 675 | "quote", 676 | "unicode-ident", 677 | ] 678 | 679 | [[package]] 680 | name = "termcolor" 681 | version = "1.1.3" 682 | source = "registry+https://github.com/rust-lang/crates.io-index" 683 | checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" 684 | dependencies = [ 685 | "winapi-util", 686 | ] 687 | 688 | [[package]] 689 | name = "textwrap" 690 | version = "0.11.0" 691 | source = "registry+https://github.com/rust-lang/crates.io-index" 692 | checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" 693 | dependencies = [ 694 | "unicode-width", 695 | ] 696 | 697 | [[package]] 698 | name = "thiserror" 699 | version = "1.0.37" 700 | source = "registry+https://github.com/rust-lang/crates.io-index" 701 | checksum = "10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e" 702 | dependencies = [ 703 | "thiserror-impl", 704 | ] 705 | 706 | [[package]] 707 | name = "thiserror-impl" 708 | version = "1.0.37" 709 | source = "registry+https://github.com/rust-lang/crates.io-index" 710 | checksum = "982d17546b47146b28f7c22e3d08465f6b8903d0ea13c1660d9d84a6e7adcdbb" 711 | dependencies = [ 712 | "proc-macro2", 713 | "quote", 714 | "syn", 715 | ] 716 | 717 | [[package]] 718 | name = "time" 719 | version = "0.1.45" 720 | source = "registry+https://github.com/rust-lang/crates.io-index" 721 | checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a" 722 | dependencies = [ 723 | "libc", 724 | "wasi", 725 | "winapi 0.3.9", 726 | ] 727 | 728 | [[package]] 729 | name = "tinyvec" 730 | version = "1.6.0" 731 | source = "registry+https://github.com/rust-lang/crates.io-index" 732 | checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" 733 | dependencies = [ 734 | "tinyvec_macros", 735 | ] 736 | 737 | [[package]] 738 | name = "tinyvec_macros" 739 | version = "0.1.0" 740 | source = "registry+https://github.com/rust-lang/crates.io-index" 741 | checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" 742 | 743 | [[package]] 744 | name = "typenum" 745 | version = "1.16.0" 746 | source = "registry+https://github.com/rust-lang/crates.io-index" 747 | checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" 748 | 749 | [[package]] 750 | name = "ucd-trie" 751 | version = "0.1.5" 752 | source = "registry+https://github.com/rust-lang/crates.io-index" 753 | checksum = "9e79c4d996edb816c91e4308506774452e55e95c3c9de07b6729e17e15a5ef81" 754 | 755 | [[package]] 756 | name = "unicode-bidi" 757 | version = "0.3.8" 758 | source = "registry+https://github.com/rust-lang/crates.io-index" 759 | checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992" 760 | 761 | [[package]] 762 | name = "unicode-ident" 763 | version = "1.0.5" 764 | source = "registry+https://github.com/rust-lang/crates.io-index" 765 | checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" 766 | 767 | [[package]] 768 | name = "unicode-normalization" 769 | version = "0.1.22" 770 | source = "registry+https://github.com/rust-lang/crates.io-index" 771 | checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921" 772 | dependencies = [ 773 | "tinyvec", 774 | ] 775 | 776 | [[package]] 777 | name = "unicode-width" 778 | version = "0.1.10" 779 | source = "registry+https://github.com/rust-lang/crates.io-index" 780 | checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" 781 | 782 | [[package]] 783 | name = "url" 784 | version = "1.7.2" 785 | source = "registry+https://github.com/rust-lang/crates.io-index" 786 | checksum = "dd4e7c0d531266369519a4aa4f399d748bd37043b00bde1e4ff1f60a120b355a" 787 | dependencies = [ 788 | "idna", 789 | "matches", 790 | "percent-encoding", 791 | ] 792 | 793 | [[package]] 794 | name = "vcpkg" 795 | version = "0.2.15" 796 | source = "registry+https://github.com/rust-lang/crates.io-index" 797 | checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" 798 | 799 | [[package]] 800 | name = "vec_map" 801 | version = "0.8.2" 802 | source = "registry+https://github.com/rust-lang/crates.io-index" 803 | checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" 804 | 805 | [[package]] 806 | name = "version_check" 807 | version = "0.9.4" 808 | source = "registry+https://github.com/rust-lang/crates.io-index" 809 | checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" 810 | 811 | [[package]] 812 | name = "wasi" 813 | version = "0.10.0+wasi-snapshot-preview1" 814 | source = "registry+https://github.com/rust-lang/crates.io-index" 815 | checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" 816 | 817 | [[package]] 818 | name = "wasm-bindgen" 819 | version = "0.2.83" 820 | source = "registry+https://github.com/rust-lang/crates.io-index" 821 | checksum = "eaf9f5aceeec8be17c128b2e93e031fb8a4d469bb9c4ae2d7dc1888b26887268" 822 | dependencies = [ 823 | "cfg-if 1.0.0", 824 | "wasm-bindgen-macro", 825 | ] 826 | 827 | [[package]] 828 | name = "wasm-bindgen-backend" 829 | version = "0.2.83" 830 | source = "registry+https://github.com/rust-lang/crates.io-index" 831 | checksum = "4c8ffb332579b0557b52d268b91feab8df3615f265d5270fec2a8c95b17c1142" 832 | dependencies = [ 833 | "bumpalo", 834 | "log", 835 | "once_cell", 836 | "proc-macro2", 837 | "quote", 838 | "syn", 839 | "wasm-bindgen-shared", 840 | ] 841 | 842 | [[package]] 843 | name = "wasm-bindgen-macro" 844 | version = "0.2.83" 845 | source = "registry+https://github.com/rust-lang/crates.io-index" 846 | checksum = "052be0f94026e6cbc75cdefc9bae13fd6052cdcaf532fa6c45e7ae33a1e6c810" 847 | dependencies = [ 848 | "quote", 849 | "wasm-bindgen-macro-support", 850 | ] 851 | 852 | [[package]] 853 | name = "wasm-bindgen-macro-support" 854 | version = "0.2.83" 855 | source = "registry+https://github.com/rust-lang/crates.io-index" 856 | checksum = "07bc0c051dc5f23e307b13285f9d75df86bfdf816c5721e573dec1f9b8aa193c" 857 | dependencies = [ 858 | "proc-macro2", 859 | "quote", 860 | "syn", 861 | "wasm-bindgen-backend", 862 | "wasm-bindgen-shared", 863 | ] 864 | 865 | [[package]] 866 | name = "wasm-bindgen-shared" 867 | version = "0.2.83" 868 | source = "registry+https://github.com/rust-lang/crates.io-index" 869 | checksum = "1c38c045535d93ec4f0b4defec448e4291638ee608530863b1e2ba115d4fff7f" 870 | 871 | [[package]] 872 | name = "winapi" 873 | version = "0.2.8" 874 | source = "registry+https://github.com/rust-lang/crates.io-index" 875 | checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" 876 | 877 | [[package]] 878 | name = "winapi" 879 | version = "0.3.9" 880 | source = "registry+https://github.com/rust-lang/crates.io-index" 881 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 882 | dependencies = [ 883 | "winapi-i686-pc-windows-gnu", 884 | "winapi-x86_64-pc-windows-gnu", 885 | ] 886 | 887 | [[package]] 888 | name = "winapi-build" 889 | version = "0.1.1" 890 | source = "registry+https://github.com/rust-lang/crates.io-index" 891 | checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" 892 | 893 | [[package]] 894 | name = "winapi-i686-pc-windows-gnu" 895 | version = "0.4.0" 896 | source = "registry+https://github.com/rust-lang/crates.io-index" 897 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 898 | 899 | [[package]] 900 | name = "winapi-util" 901 | version = "0.1.5" 902 | source = "registry+https://github.com/rust-lang/crates.io-index" 903 | checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" 904 | dependencies = [ 905 | "winapi 0.3.9", 906 | ] 907 | 908 | [[package]] 909 | name = "winapi-x86_64-pc-windows-gnu" 910 | version = "0.4.0" 911 | source = "registry+https://github.com/rust-lang/crates.io-index" 912 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 913 | 914 | [[package]] 915 | name = "ws" 916 | version = "0.7.9" 917 | source = "registry+https://github.com/rust-lang/crates.io-index" 918 | checksum = "329d3e6dd450a9c5c73024e1047f0be7e24121a68484eb0b5368977bee3cf8c3" 919 | dependencies = [ 920 | "byteorder", 921 | "bytes", 922 | "httparse", 923 | "log", 924 | "mio", 925 | "mio-extras", 926 | "rand", 927 | "sha1 0.6.1", 928 | "slab", 929 | "url", 930 | ] 931 | 932 | [[package]] 933 | name = "ws2_32-sys" 934 | version = "0.2.1" 935 | source = "registry+https://github.com/rust-lang/crates.io-index" 936 | checksum = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" 937 | dependencies = [ 938 | "winapi 0.2.8", 939 | "winapi-build", 940 | ] 941 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "src/easechat-nexus-rs", 4 | "src/easechat-nexus-v2-rs", 5 | "src/easechat-exec-rs", 6 | "src/easechat-record-rs" 7 | ] 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2019 Fang Yizhou, HDJ, Luo Jia, Woder 2 | EaseChat is licensed under the Mulan PSL v1. 3 | You can use this software according to the terms and conditions of the Mulan PSL v1. 4 | You may obtain a copy of Mulan PSL v1 at: 5 | http://license.coscl.org.cn/MulanPSL 6 | THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR 7 | IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR 8 | PURPOSE. 9 | See the Mulan PSL v1 for more details. 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EaseChat 2 | 3 | Simple message exchange network with channel-subscription based structure. 4 | EaseChat was originally designed as a chat message exchanging service for games, but its usage could be widen to debug messages 5 | and commands for maintaining. 6 | 7 | Although the first version of EaseChat Nexus may be less flexible, we deployed it on production use months ago. 8 | Its record on non-pausing and reboot-free continous execution is 3,432 hours on our mini-game server network region, since 30 Jan to 22 Jun 2019, killed mistaken by a ctrl-c quit. The network consists of ~350 endpoints and produces ~1k messages on average per second, their CPU and RAM usage being low at the same time. 9 | Players mostly suggest it 'Great' in our recent survey on this part of the game's experience. 10 | 11 | ## Project structure 12 | 13 | | Name | Description | 14 | |:----|:-----------| 15 | | easechat-client-j | Netty-based Java implementation of EaseChat client oriented to production | 16 | | easechat-exec-rs | (In progress) Complete cli application of EaseChat in Rust | 17 | | easechat-nexus-rs | First version of Rust EaseChat nexus impl using mio and ws | 18 | | easechat-nexus-v2-rs | (In progress) Redesigned Rust EaseChat protocol library intended for general use | 19 | | easechat-record-rs | (In progress) Simple Rust cli EaseChat client app, connect to nexus and save message via SQLite | 20 | 21 | ## Run EaseChat Nexus 22 | 23 | 1. Install [rust](https://rust-lang.org/), or run `rustup update` if already installed. 24 | 2. Execute `cargo run -p ease_chat_nexus` in project root. 25 | 26 | Step 1 is necessary because this EaseChat Nexus implementation requires rust edition 2018 installed. 27 | This implementation is written in rust version 1.32.0-stable. 28 | 29 | ## Protocol specification 30 | 31 | [中文协议文档](https://github.com/EaseCation/ease_chat/blob/master/protocol-zh.md) 32 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | net.easecation 8 | easechat 9 | 1.0-SNAPSHOT 10 | pom 11 | 12 | 13 | src/easechat-client-j 14 | 15 | 16 | -------------------------------------------------------------------------------- /protocol-zh.md: -------------------------------------------------------------------------------- 1 | # Protocol 协议说明 2 | 3 | ### 基本: 4 | 5 | - 本协议暂时基于WebSocket,属于内网协议 6 | - 为方便调试,直接通过传递字符串进行信息交换,在字符串中使用`|`分割信息体 7 | - 未来将使用可靠性可选的、基于UDP的虚拟连接协议,以字节方式传输;加强安全性,以便开放到公网 8 | 9 | ### 协议种类: 10 | 11 | pid位于数据的第一部分。一般由一个数字与一个简写字母组成。数字代表协议版本号,后方字母代表协议分类。 12 | 13 | Client发送给Nexus的有以下类型: 14 | 15 | - `1h` Hello 握手 16 | - `1c` Channel 订阅频道 17 | - `1t` Transmit 发送消息 18 | - `1d` Disconnect 断开连接 19 | 20 | Nexus主动发送给Client的有以下类型: 21 | 22 | - `1r` Receive 接收消息 23 | 24 | ## 协议内容: 25 | 26 | `Tip:为了防止注入,涉及到第三方可编辑的字符串部分,都特别加入了字符串长度用于检验。` 27 | 28 | ### `1h` Hello 握手: 29 | 30 | 组合方式:1h|名称`长度(字节)`|名称 31 | 32 | _握手是为了上报服务端,该客户端的`名称`,用于发送消息时告知其他客户端消息的来源。_ 33 | 34 | 例如:`1h|12|abcdef123456` 35 | 36 | ### `1c` Channel 订阅频道: 37 | 38 | 组合方式:1c|频道名字`长度(字节)`|频道名字|需要订阅的时间(秒部分)|需要订阅的时间(纳秒部分) 39 | 40 | _订阅就像续命,客户端需要定时订阅频道,来告知服务端需要向我发送哪些频道的消息。_ 41 | 42 | 例如: 43 | 订阅c/lobby频道五分钟 `1c|7|c/lobby|300|0` 44 | 45 | ### `1t` Transmit 发送消息: 46 | 47 | 组合方式:1t|频道`长度(字节)`|频道名字|消息`长度(字节)`|消息 48 | 49 | _客户端发送给服务端_ 50 | 51 | 例如: 52 | 发送helloworld到c/lobby频道 `1t|7|c/lobby|10|helloworld` 53 | 54 | ### `1d` Disconnect 断开连接: 55 | 56 | 组合方式:1d|理由`长度(字节)`|理由 57 | 58 | _发送后,应由服务端断开连接_ 59 | 60 | 例如:`1d|11|just logout` 61 | 62 | ### `1r` Receive 接收消息: 63 | 64 | 组合方式:1r|消息来源字符串`长度(字节)`|消息来源|频道字符串`长度(字节)`|频道|消息字符串`长度(字节)`|消息 65 | 66 | _客户端订阅后,由中转枢纽主动发送给客户端。中转枢纽将忽略所有客户端发来的1r类型消息。_ 67 | -------------------------------------------------------------------------------- /src/easechat-client-j/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | application 3 | id("ecbuild.java-conventions") 4 | } 5 | 6 | application { 7 | mainClass = "net.easecation.easechat.Main" 8 | } 9 | 10 | dependencies { 11 | api(libs.netty.all) 12 | } 13 | 14 | description = "easechat-client-j" 15 | -------------------------------------------------------------------------------- /src/easechat-client-j/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | net.easecation 8 | easechat-client-j 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 21 13 | 21 14 | UTF-8 15 | 16 | 17 | 18 | 19 | io.netty 20 | netty-all 21 | 4.1.107.Final 22 | 23 | 24 | 25 | 26 | ${project.artifactId} 27 | 28 | 29 | org.apache.maven.plugins 30 | maven-shade-plugin 31 | 3.6.0 32 | 33 | 34 | package 35 | 36 | shade 37 | 38 | 39 | 40 | 41 | net.easecation.easechat.Main 42 | 43 | 44 | ${project.build.directory}/dependency-reduced-pom.xml 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /src/easechat-client-j/src/main/java/net/easecation/easechat/Main.java: -------------------------------------------------------------------------------- 1 | package net.easecation.easechat; 2 | 3 | import net.easecation.easechat.api.message.AutoSubChannelMessage; 4 | import net.easecation.easechat.api.message.TransmitMessage; 5 | import net.easecation.easechat.network.EaseChatClient; 6 | 7 | import java.net.URI; 8 | import java.util.Arrays; 9 | import java.util.Objects; 10 | 11 | public class Main { 12 | 13 | public static void main(String[] args) { 14 | 15 | EaseChatClient c = startClient(); 16 | 17 | try { 18 | Thread.sleep(5000); 19 | } catch (InterruptedException e) { 20 | e.printStackTrace(); 21 | } 22 | 23 | c.shutdown(); 24 | 25 | System.exit(0); 26 | 27 | EaseChatClient[] clients = new EaseChatClient[1000]; 28 | 29 | //压力测试 统计并显示已成功握手的连接数量 30 | new Thread(() -> { 31 | while(true) { 32 | try { 33 | System.out.println("连接成功数:" + Arrays.stream(clients).filter(Objects::nonNull).filter(EaseChatClient::isHandshake).count()); 34 | } catch (Exception e) { 35 | e.printStackTrace(); 36 | } 37 | try { 38 | Thread.sleep(1000); 39 | } catch (InterruptedException e) { 40 | e.printStackTrace(); 41 | } 42 | } 43 | }).start(); 44 | 45 | //压力测试 定时发送消息 46 | new Thread(() -> { 47 | while(true) { 48 | Arrays.stream(clients).filter(Objects::nonNull).filter(EaseChatClient::isHandshake).forEach(client -> { 49 | client.getSender().sendSyncTransmitMessage(new TransmitMessage("buglet", "TEST!$$!" + System.currentTimeMillis())); 50 | }); 51 | try { 52 | Thread.sleep(1000); 53 | } catch (InterruptedException e) { 54 | e.printStackTrace(); 55 | } 56 | } 57 | }).start(); 58 | 59 | //压力测试 创建大批量连接 60 | for (int i = 0; i < clients.length; i++) { 61 | try { 62 | clients[i] = startClient(); 63 | } catch (Exception e) { 64 | e.printStackTrace(); 65 | } 66 | } 67 | 68 | } 69 | 70 | private static EaseChatClient startClient() { 71 | EaseChatClient client = new EaseChatClient("ChinaHDJ", URI.create("wx://192.168.31.122:6500"), System.out::println); 72 | 73 | try { 74 | client.start(); 75 | } catch (Exception e) { 76 | e.printStackTrace(); 77 | System.exit(0); 78 | } 79 | client.getSender().sendSyncChannelMessage(new AutoSubChannelMessage("buglet", 5), f -> client.getLogger().info("已订阅频道!")); 80 | client.getSender().sendSyncChannelMessage(new AutoSubChannelMessage("lobby/main", 5), f -> client.getLogger().info("已订阅频道!")); 81 | 82 | return client; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/easechat-client-j/src/main/java/net/easecation/easechat/api/Logger.java: -------------------------------------------------------------------------------- 1 | package net.easecation.easechat.api; 2 | 3 | /** 4 | * author: MagicDroidX 5 | * Nukkit Project 6 | */ 7 | public interface Logger { 8 | 9 | void emergency(String message); 10 | 11 | void alert(String message); 12 | 13 | void critical(String message); 14 | 15 | void error(String message); 16 | 17 | void warning(String message); 18 | 19 | void notice(String message); 20 | 21 | void info(String message); 22 | 23 | void debug(String message); 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/easechat-client-j/src/main/java/net/easecation/easechat/api/Message.java: -------------------------------------------------------------------------------- 1 | package net.easecation.easechat.api; 2 | 3 | /* 4 | * 封装一条 消息数据 5 | * */ 6 | public interface Message { 7 | String MESSAGE_HELLO = "1h"; //客户端向服务端 握手 8 | String MESSAGE_CHANNEL = "1c"; // 客户端向服务端 订阅频道 9 | String MESSAGE_TRANSMIT = "1t"; // 客户端向服务端发送消息 10 | String MESSAGE_RECEIVE = "1r"; // 服务端 向 客户端发送的数据 11 | String MESSAGE_DISCONNECT = "1d"; // 客户端主动断开与服务端的连接 12 | 13 | int getMessageLength(); 14 | 15 | String getMessageType(); 16 | } 17 | -------------------------------------------------------------------------------- /src/easechat-client-j/src/main/java/net/easecation/easechat/api/MessageReceiver.java: -------------------------------------------------------------------------------- 1 | package net.easecation.easechat.api; 2 | 3 | import net.easecation.easechat.api.message.ReceiveMessage; 4 | import net.easecation.easechat.network.EaseChatClient; 5 | 6 | /* 7 | * 消息接收器 8 | * */ 9 | public class MessageReceiver { 10 | private Listener listener; 11 | private final EaseChatClient client; 12 | 13 | public MessageReceiver(EaseChatClient client, Listener listener){ 14 | this.client = client; 15 | this.listener = listener; 16 | } 17 | 18 | public void setListener(Listener listener) { 19 | if (this.listener == null){ 20 | this.listener = listener; 21 | } 22 | } 23 | 24 | public void receive(ReceiveMessage message){ 25 | if (listener != null) listener.listen(message); 26 | } 27 | 28 | /* 29 | * 实现 Listener 接口处理接数据接收 30 | * */ 31 | @FunctionalInterface 32 | public interface Listener{ 33 | void listen(ReceiveMessage logger); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/easechat-client-j/src/main/java/net/easecation/easechat/api/MessageSender.java: -------------------------------------------------------------------------------- 1 | package net.easecation.easechat.api; 2 | 3 | import net.easecation.easechat.api.message.AutoSubChannelMessage; 4 | import net.easecation.easechat.api.message.ChannelMessage; 5 | import net.easecation.easechat.api.message.HelloMessage; 6 | import net.easecation.easechat.api.message.TransmitMessage; 7 | import io.netty.channel.Channel; 8 | 9 | import io.netty.channel.ChannelFuture; 10 | import io.netty.util.concurrent.Future; 11 | import net.easecation.easechat.network.EaseChatClient; 12 | 13 | import java.util.Timer; 14 | import java.util.TimerTask; 15 | 16 | public class MessageSender { 17 | 18 | private final EaseChatClient client; 19 | private final Channel channel; 20 | private final Timer timer; 21 | 22 | public Channel getChannel() { 23 | return channel; 24 | } 25 | 26 | public MessageSender(EaseChatClient client, Channel channel) { 27 | this.client = client; 28 | this.channel = channel; 29 | this.timer = new Timer(); 30 | } 31 | 32 | public void stopTimer() { 33 | timer.cancel(); 34 | } 35 | 36 | private void catchHandleAutoSubChannelMessage(Message message) { 37 | if (message instanceof AutoSubChannelMessage) { 38 | AutoSubChannelMessage autoSubChannelMessage = (AutoSubChannelMessage) message; 39 | timer.schedule(new AutoSubTimerTask(autoSubChannelMessage), autoSubChannelMessage.getSubscriptionTime() * 900); 40 | } 41 | } 42 | 43 | private boolean checkHandshake(Message message) { 44 | if (message instanceof HelloMessage) return true; 45 | if (!client.isHandshake()) { 46 | client.getInitChannelMessages().add(message); 47 | return false; 48 | } 49 | return true; 50 | } 51 | 52 | /** 53 | * 发送消息 同步方式 不使用Result处理返回值 54 | */ 55 | public boolean sendSyncMessage(Message message) { 56 | if (!checkHandshake(message)) return true; 57 | catchHandleAutoSubChannelMessage(message); 58 | try { 59 | return getChannel().writeAndFlush(message).sync().isSuccess(); 60 | } catch (InterruptedException e) { 61 | e.printStackTrace(); 62 | return false; 63 | } 64 | } 65 | 66 | /** 67 | * 发送消息 同步方式 使用Result处理返回值 68 | */ 69 | public void sendSyncMessage(Message message, Result result) { 70 | if (!checkHandshake(message)) return; 71 | catchHandleAutoSubChannelMessage(message); 72 | 73 | try { 74 | ChannelFuture future = getChannel().writeAndFlush(message).sync(); 75 | 76 | if (result != null) result.handle(future); 77 | } catch (InterruptedException e) { 78 | e.printStackTrace(); 79 | } 80 | } 81 | 82 | /** 83 | * 异步发送 84 | */ 85 | public void sendAsyncMessage(Message message, Result result) { 86 | if (!checkHandshake(message)) return; 87 | catchHandleAutoSubChannelMessage(message); 88 | 89 | this.channel.writeAndFlush(message).addListener(result::handle); 90 | } 91 | 92 | public boolean sendSyncChannelMessage(ChannelMessage message) { 93 | return sendSyncMessage(message); 94 | } 95 | 96 | public void sendSyncChannelMessage(ChannelMessage message, Result result) { 97 | sendSyncMessage(message, result); 98 | } 99 | 100 | public boolean sendSyncHelloMessage(HelloMessage message) { 101 | return sendSyncMessage(message); 102 | } 103 | 104 | public void sendSyncHelloMessage(HelloMessage message, Result result) { 105 | sendSyncMessage(message, result); 106 | } 107 | 108 | public boolean sendSyncTransmitMessage(TransmitMessage message) { 109 | return sendSyncMessage(message); 110 | } 111 | 112 | public void sendSyncTransmitMessage(TransmitMessage message, Result result) { 113 | sendSyncMessage(message, result); 114 | } 115 | 116 | public void sendAsyncHelloMessage(HelloMessage message, Result result) { 117 | sendAsyncMessage(message, result); 118 | } 119 | 120 | public void sendAsyncChannelMessage(ChannelMessage message, Result result) { 121 | sendAsyncMessage(message, result); 122 | } 123 | 124 | public void sendAsyncTransmitMessage(TransmitMessage message, Result result) { 125 | sendAsyncMessage(message, result); 126 | } 127 | 128 | public class AutoSubTimerTask extends TimerTask { 129 | 130 | private final AutoSubChannelMessage message; 131 | 132 | public AutoSubTimerTask(AutoSubChannelMessage message) { 133 | this.message = message; 134 | message.setTimerTask(this); 135 | } 136 | 137 | @Override 138 | public void run() { 139 | if (message.isCloseAutoSub()) this.cancel(); 140 | 141 | MessageSender.this.sendSyncChannelMessage(message); 142 | } 143 | } 144 | 145 | @FunctionalInterface 146 | public interface Result { 147 | void handle(Future future) throws InterruptedException; 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/easechat-client-j/src/main/java/net/easecation/easechat/api/SimpleLogger.java: -------------------------------------------------------------------------------- 1 | package net.easecation.easechat.api; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Date; 5 | 6 | public class SimpleLogger implements Logger { 7 | 8 | @Override 9 | public void emergency(String message) { 10 | System.out.println(getTimeFormat() + "[EMERGENCY] " + message); 11 | } 12 | 13 | @Override 14 | public void alert(String message) { 15 | System.out.println(getTimeFormat() + "[ALERT] " + message); 16 | } 17 | 18 | @Override 19 | public void critical(String message) { 20 | System.out.println(getTimeFormat() + "[CRITICAL] " + message); 21 | } 22 | 23 | @Override 24 | public void error(String message) { 25 | System.out.println(getTimeFormat() + "[ERROR] " + message); 26 | } 27 | 28 | @Override 29 | public void warning(String message) { 30 | System.out.println(getTimeFormat() + "[WARNING] " + message); 31 | } 32 | 33 | @Override 34 | public void notice(String message) { 35 | System.out.println(getTimeFormat() + "[NOTICE] " + message); 36 | } 37 | 38 | @Override 39 | public void info(String message) { 40 | System.out.println(getTimeFormat() + "[INFO] " + message); 41 | } 42 | 43 | @Override 44 | public void debug(String message) { 45 | System.out.println(getTimeFormat() + "[DEBUG] " + message); 46 | } 47 | 48 | private String getTimeFormat() { 49 | Date now = new Date(); 50 | return new SimpleDateFormat("HH:mm:ss ").format(now); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/easechat-client-j/src/main/java/net/easecation/easechat/api/message/AutoSubChannelMessage.java: -------------------------------------------------------------------------------- 1 | package net.easecation.easechat.api.message; 2 | 3 | import net.easecation.easechat.api.MessageSender; 4 | 5 | public class AutoSubChannelMessage extends ChannelMessage { 6 | private boolean closeAutoSub; 7 | private MessageSender.AutoSubTimerTask timerTask; 8 | 9 | public AutoSubChannelMessage(String channelName) { 10 | super(channelName); 11 | } 12 | 13 | public AutoSubChannelMessage(String channelName, int subscriptionTime) { 14 | super(channelName, subscriptionTime); 15 | } 16 | 17 | public AutoSubChannelMessage(String channelName, int subscriptionTime, int subscriptionTimeNS) { 18 | super(channelName, subscriptionTime, subscriptionTimeNS); 19 | } 20 | 21 | public void setCloseAutoSub(boolean closeAutoSub) { 22 | this.closeAutoSub = closeAutoSub; 23 | } 24 | 25 | public boolean isCloseAutoSub() { 26 | return closeAutoSub; 27 | } 28 | 29 | public MessageSender.AutoSubTimerTask getTimerTask() { 30 | return timerTask; 31 | } 32 | 33 | public void setTimerTask(MessageSender.AutoSubTimerTask timerTask) { 34 | if(this.timerTask == null) this.timerTask = timerTask; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/easechat-client-j/src/main/java/net/easecation/easechat/api/message/ChannelMessage.java: -------------------------------------------------------------------------------- 1 | package net.easecation.easechat.api.message; 2 | 3 | import net.easecation.easechat.api.Message; 4 | 5 | /** 6 | * 订阅消息封装 7 | */ 8 | public class ChannelMessage implements Message { 9 | 10 | private final String channelName; 11 | private final int subscriptionTime; 12 | private final int subscriptionTimeNS; 13 | 14 | public final static int DEFAULT_SUBSCRIPTION_TIME = 600; //默认订阅时间 十分钟 15 | 16 | public final static int DEFAULT_SUBSCRIPTION_TIME_NS = 0; //默认订阅时间(纳秒)0 17 | 18 | public ChannelMessage(String channelName){ 19 | this(channelName, DEFAULT_SUBSCRIPTION_TIME); 20 | } 21 | 22 | public ChannelMessage(String channelName, int subscriptionTime){ 23 | this(channelName, subscriptionTime, DEFAULT_SUBSCRIPTION_TIME_NS); 24 | } 25 | 26 | public ChannelMessage(String channelName, int subscriptionTime, int subscriptionTimeNS){ 27 | this.channelName = channelName; 28 | this.subscriptionTime = subscriptionTime; 29 | this.subscriptionTimeNS = subscriptionTimeNS; 30 | } 31 | 32 | public int getSubscriptionTime() { 33 | return subscriptionTime; 34 | } 35 | 36 | @Override 37 | public int getMessageLength() { 38 | return channelName.getBytes().length; 39 | } 40 | 41 | @Override 42 | public String getMessageType() { 43 | return Message.MESSAGE_CHANNEL; 44 | } 45 | 46 | @Override 47 | public String toString() { 48 | return String.join( 49 | "|", 50 | getMessageType(), 51 | String.valueOf(getMessageLength()), 52 | this.channelName, 53 | String.valueOf(this.subscriptionTime), 54 | String.valueOf(this.subscriptionTimeNS) 55 | ); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/easechat-client-j/src/main/java/net/easecation/easechat/api/message/DisconnectMessage.java: -------------------------------------------------------------------------------- 1 | package net.easecation.easechat.api.message; 2 | 3 | import net.easecation.easechat.api.Message; 4 | 5 | /* 6 | * 断开连接 封装 7 | * */ 8 | public class DisconnectMessage implements Message { 9 | private final String text; 10 | 11 | public DisconnectMessage(String text){ 12 | this.text = text; 13 | } 14 | 15 | @Override 16 | public String getMessageType() { 17 | return Message.MESSAGE_DISCONNECT; 18 | } 19 | 20 | @Override 21 | public int getMessageLength() { 22 | return text.getBytes().length; 23 | } 24 | 25 | @Override 26 | public String toString() { 27 | return String.join("|", getMessageType(), String.valueOf(getMessageLength()), text); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/easechat-client-j/src/main/java/net/easecation/easechat/api/message/HelloMessage.java: -------------------------------------------------------------------------------- 1 | package net.easecation.easechat.api.message; 2 | 3 | import net.easecation.easechat.api.Message; 4 | 5 | /* 6 | * 握手消息 封装 7 | * */ 8 | public class HelloMessage implements Message { 9 | private final String text; 10 | 11 | public HelloMessage(String text){ 12 | this.text = text; 13 | } 14 | 15 | @Override 16 | public String getMessageType() { 17 | return Message.MESSAGE_HELLO; 18 | } 19 | 20 | @Override 21 | public int getMessageLength() { 22 | return text.getBytes().length; 23 | } 24 | 25 | @Override 26 | public String toString() { 27 | return String.join("|", getMessageType(), String.valueOf(getMessageLength()), text); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/easechat-client-j/src/main/java/net/easecation/easechat/api/message/ReceiveMessage.java: -------------------------------------------------------------------------------- 1 | package net.easecation.easechat.api.message; 2 | 3 | import net.easecation.easechat.api.Message; 4 | 5 | /* 6 | * 消息接收数据 封装 7 | * */ 8 | public class ReceiveMessage implements Message { 9 | private final String text; 10 | private final String channelName; 11 | private final String form; 12 | 13 | public static ReceiveMessage valueOf(String source){ 14 | String[] data = source.split("\\|",7); 15 | 16 | if (!data[0].equals(MESSAGE_RECEIVE)){ 17 | throw new IllegalArgumentException("协议头有误"); 18 | } 19 | if (data[2].getBytes().length != Integer.parseInt(data[1])){ 20 | throw new IllegalArgumentException("协议头有误"); 21 | } 22 | 23 | if (data[4].getBytes().length != Integer.parseInt(data[3])){ 24 | throw new IllegalArgumentException("协议头有误"); 25 | } 26 | 27 | if (data[6].getBytes().length != Integer.parseInt(data[5])){ 28 | throw new IllegalArgumentException("协议头有误"); 29 | } 30 | 31 | return new ReceiveMessage(data[2], data[4], data[6]); 32 | } 33 | 34 | private ReceiveMessage(String form, String channelName, String text){ 35 | this.form = form; 36 | this.channelName = channelName; 37 | this.text = text; 38 | } 39 | 40 | public String getForm() { 41 | return form; 42 | } 43 | 44 | public String getChannelName() { 45 | return channelName; 46 | } 47 | 48 | public String getText() { 49 | return text; 50 | } 51 | 52 | @Override 53 | public int getMessageLength() { 54 | return text.getBytes().length; 55 | } 56 | 57 | @Override 58 | public String getMessageType() { 59 | return Message.MESSAGE_RECEIVE; 60 | } 61 | 62 | @Override 63 | public String toString() { 64 | return String.join( 65 | "|", 66 | getMessageType(), 67 | String.valueOf(form.getBytes().length), 68 | getForm(), 69 | String.valueOf(channelName.getBytes().length), 70 | getChannelName(), 71 | String.valueOf(text.getBytes().length), 72 | getText() 73 | ); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/easechat-client-j/src/main/java/net/easecation/easechat/api/message/TransmitMessage.java: -------------------------------------------------------------------------------- 1 | package net.easecation.easechat.api.message; 2 | 3 | import net.easecation.easechat.api.Message; 4 | 5 | /* 6 | * 发送消息 封装 7 | * */ 8 | public class TransmitMessage implements Message { 9 | 10 | private final String channelName; 11 | private final String text; 12 | 13 | public TransmitMessage(String channelName, String text){ 14 | if (channelName == null || channelName.isEmpty()){ 15 | throw new IllegalArgumentException("channel 不能为空"); 16 | } 17 | 18 | if (text == null || text.isEmpty()){ 19 | throw new IllegalArgumentException("text 不能为空"); 20 | } 21 | 22 | this.channelName = channelName; 23 | this.text = text; 24 | } 25 | 26 | @Override 27 | public int getMessageLength() { 28 | return text.getBytes().length; 29 | } 30 | 31 | @Override 32 | public String getMessageType() { 33 | return Message.MESSAGE_TRANSMIT; 34 | } 35 | 36 | @Override 37 | public String toString() { 38 | return String.join( 39 | "|", 40 | getMessageType(), 41 | String.valueOf(this.channelName.getBytes().length), 42 | this.channelName, 43 | String.valueOf(getMessageLength()), 44 | text 45 | ); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/easechat-client-j/src/main/java/net/easecation/easechat/network/EaseChatClient.java: -------------------------------------------------------------------------------- 1 | package net.easecation.easechat.network; 2 | 3 | import io.netty.bootstrap.Bootstrap; 4 | import io.netty.channel.*; 5 | import io.netty.channel.nio.NioEventLoopGroup; 6 | import io.netty.channel.socket.SocketChannel; 7 | import io.netty.channel.socket.nio.NioSocketChannel; 8 | import io.netty.handler.codec.http.*; 9 | import io.netty.handler.codec.http.websocketx.*; 10 | 11 | import net.easecation.easechat.api.*; 12 | import net.easecation.easechat.api.message.ChannelMessage; 13 | import net.easecation.easechat.api.message.DisconnectMessage; 14 | 15 | import java.net.URI; 16 | import java.util.ArrayList; 17 | import java.util.Arrays; 18 | import java.util.List; 19 | import java.util.function.Consumer; 20 | 21 | public class EaseChatClient { 22 | 23 | private EventLoopGroup loopGroup; 24 | private Channel channel = null; 25 | private boolean isHandshake = false; 26 | private MessageSender sender; 27 | private final MessageReceiver receiver; 28 | private Logger logger = new SimpleLogger(); 29 | private final URI websocketURI; 30 | private final List initChannelMessages = new ArrayList<>(); 31 | 32 | /* 33 | * name 用与 向服务端发起1h握手协议时必须带的参数 34 | * */ 35 | public EaseChatClient(String name, URI websocketURI, MessageReceiver.Listener listener) { 36 | if (name == null || name.isEmpty()) throw new IllegalArgumentException("带个 name 参数啊"); 37 | this.name = name; 38 | if (websocketURI == null) { 39 | throw new IllegalArgumentException("url不能为空"); 40 | } 41 | 42 | this.websocketURI = websocketURI; 43 | this.receiver = new MessageReceiver(this, listener); 44 | } 45 | 46 | public EaseChatClient(String name, URI websocketURI, ChannelMessage[] messages, MessageReceiver.Listener listener) { 47 | this(name, websocketURI, listener); 48 | this.initChannelMessages.addAll(Arrays.asList(messages)); 49 | } 50 | 51 | public Logger getLogger() { 52 | return logger; 53 | } 54 | 55 | public void setLogger(Logger logger) { 56 | this.logger = logger; 57 | } 58 | 59 | private final String name; 60 | 61 | String getName() { 62 | return name; 63 | } 64 | 65 | public MessageSender getSender() { 66 | return sender; 67 | } 68 | 69 | MessageReceiver getReceiver() { 70 | return receiver; 71 | } 72 | 73 | public boolean isHandshake() { 74 | return isHandshake; 75 | } 76 | 77 | public void setHandshake(boolean handshake) { 78 | isHandshake = handshake; 79 | } 80 | 81 | public List getInitChannelMessages() { 82 | return initChannelMessages; 83 | } 84 | 85 | public void start() throws Exception { 86 | start(null); 87 | } 88 | 89 | public void start(Consumer setup) throws Exception { 90 | Bootstrap bootstrap = new Bootstrap(); 91 | if (setup != null) { 92 | setup.accept(bootstrap); 93 | } 94 | if (bootstrap.config().group() == null) { 95 | loopGroup = new NioEventLoopGroup(); 96 | bootstrap.group(loopGroup) 97 | .channel(NioSocketChannel.class); 98 | } 99 | bootstrap 100 | .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024 * 1024)) 101 | .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000) 102 | .handler(new ChannelInitializer() { 103 | @Override 104 | protected void initChannel(SocketChannel channel) { 105 | channel.pipeline() 106 | .addLast(new HttpClientCodec()) 107 | .addLast(new HttpObjectAggregator(65535)) 108 | .addLast(new WebSocketFrameAggregator(65535)) 109 | .addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(websocketURI, WebSocketVersion.V13, null, true, new DefaultHttpHeaders()))) 110 | .addLast(new MessageCodec()) 111 | .addLast(new MessageHandler(EaseChatClient.this)); 112 | } 113 | }); 114 | try { 115 | this.channel = bootstrap.connect(websocketURI.getHost(), websocketURI.getPort()).sync().channel(); 116 | this.sender = new MessageSender(this, channel); 117 | getLogger().info("Nexus WebSocket 连接成功"); 118 | } catch (Exception e) { 119 | getLogger().warning("Nexus WebSocket 连接失败"); 120 | getLogger().warning(e.getMessage()); 121 | throw e; 122 | } 123 | } 124 | 125 | /* 126 | * 关闭EaseChatClient 同步 127 | * */ 128 | public boolean shutdown() { 129 | if (this.getSender() != null) { 130 | this.getSender().sendSyncMessage(new DisconnectMessage("shutdown")); 131 | try { 132 | channel.closeFuture().sync().isSuccess(); 133 | } catch (InterruptedException e) { 134 | e.printStackTrace(); 135 | return false; 136 | } 137 | } 138 | 139 | if (loopGroup == null) { 140 | return true; 141 | } 142 | return loopGroup.shutdownGracefully().isSuccess(); 143 | } 144 | 145 | public boolean isActive() { 146 | return channel != null && channel.isActive(); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/easechat-client-j/src/main/java/net/easecation/easechat/network/MessageCodec.java: -------------------------------------------------------------------------------- 1 | package net.easecation.easechat.network; 2 | 3 | import io.netty.channel.ChannelHandlerContext; 4 | import io.netty.handler.codec.MessageToMessageCodec; 5 | import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; 6 | import net.easecation.easechat.api.Message; 7 | import net.easecation.easechat.api.message.ReceiveMessage; 8 | 9 | import java.util.List; 10 | 11 | public class MessageCodec extends MessageToMessageCodec{ 12 | @Override 13 | protected void decode(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame frame, List list) throws Exception { 14 | list.add(ReceiveMessage.valueOf(frame.text())); 15 | } 16 | 17 | @Override 18 | protected void encode(ChannelHandlerContext channelHandlerContext, Message message, List list) throws Exception { 19 | list.add(new TextWebSocketFrame(message.toString())); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/easechat-client-j/src/main/java/net/easecation/easechat/network/MessageHandler.java: -------------------------------------------------------------------------------- 1 | package net.easecation.easechat.network; 2 | 3 | import io.netty.channel.*; 4 | import net.easecation.easechat.api.Message; 5 | import net.easecation.easechat.api.message.HelloMessage; 6 | import net.easecation.easechat.api.message.ReceiveMessage; 7 | 8 | import static io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_COMPLETE; 9 | import static io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_ISSUED; 10 | 11 | /* 12 | * 用与处理 消息接收 13 | * */ 14 | public class MessageHandler extends SimpleChannelInboundHandler { 15 | 16 | private final EaseChatClient client; 17 | 18 | MessageHandler(EaseChatClient client){ 19 | this.client = client; 20 | } 21 | 22 | @Override 23 | public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { 24 | super.userEventTriggered(ctx, evt); 25 | 26 | if (HANDSHAKE_ISSUED.equals(evt)) { 27 | client.getLogger().info("正在向 Nexus WebSocket 发送TCP握手"); 28 | } 29 | 30 | if (HANDSHAKE_COMPLETE.equals(evt)) { 31 | client.getLogger().info("Nexus WebSocket TCP握手完成 即将发送1h握手"); 32 | 33 | while (client.getSender() == null) {} 34 | 35 | client.getSender().sendSyncHelloMessage(new HelloMessage(client.getName()), future -> { 36 | if (future.isSuccess()){ 37 | client.setHandshake(true); 38 | client.getLogger().info("1h握手数据 发送成功 开始发送握手成功前未发送的信息包"); 39 | for (Message message : client.getInitChannelMessages()){ 40 | client.getSender().sendSyncMessage(message); 41 | client.getLogger().info("补充发送:" + message.toString()); 42 | } 43 | client.getInitChannelMessages().clear(); 44 | } else { 45 | client.getLogger().warning("握手失败 即将关闭 EaseChatClient"); 46 | if (!client.shutdown()) throw new InterruptedException("haha"); // 暴力关闭 -1s 47 | } 48 | }); 49 | } 50 | } 51 | 52 | protected void channelRead0(ChannelHandlerContext ctx, ReceiveMessage msg) throws Exception { 53 | client.getReceiver().receive(msg); 54 | } 55 | 56 | } -------------------------------------------------------------------------------- /src/easechat-exec-rs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "easechat-exec" 3 | version = "0.0.0" 4 | authors = ["luojia65 "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | easechat-nexus = { version = "*", path = "../easechat-nexus-v2-rs" } 9 | -------------------------------------------------------------------------------- /src/easechat-exec-rs/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("Hello, world!"); 3 | } 4 | -------------------------------------------------------------------------------- /src/easechat-nexus-rs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ease_chat_nexus" 3 | version = "0.0.2" 4 | authors = ["luojia65 "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | ws = "0.7.9" 9 | pest = "*" 10 | pest_derive = "*" 11 | -------------------------------------------------------------------------------- /src/easechat-nexus-rs/examples/console_parser.rs: -------------------------------------------------------------------------------- 1 | use pest_derive::Parser; 2 | use pest::Parser; 3 | 4 | #[derive(Parser)] 5 | #[grammar = "../src/console_rule.pest"] 6 | struct NexusParser; 7 | 8 | fn main() { 9 | loop { 10 | let mut buf = String::new(); 11 | std::io::stdin().read_line(&mut buf).unwrap(); 12 | match NexusParser::parse(Rule::command, &buf.trim()) { 13 | Ok(mut pairs) => match pairs.next().map(|p| p.as_rule()) { 14 | Some(Rule::cmd_stop_head) => std::process::exit(0), 15 | Some(Rule::cmd_list_head) => println!("list!!"), 16 | Some(Rule::cmd_push_head) => if let (Some(sender), Some(chan), Some(msg)) 17 | = (pairs.next(), pairs.next(), pairs.next()) { 18 | println!("sender: [{}], chan: [{}], msg: [{}]", sender.as_str(), chan.as_str(), msg.as_str()); 19 | }, 20 | _ => eprintln!("unreachable expression, this is a bug!") 21 | }, 22 | Err(e) => { 23 | eprintln!("err: {}", e); 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/easechat-nexus-rs/src/console_rule.pest: -------------------------------------------------------------------------------- 1 | space_char = _{ " " | "\t" } 2 | nonspace_char = _{ !space_char ~ ANY } 3 | space = _{ ( space_char ) * } 4 | nonspace_string = _{ ( nonspace_char ) + } 5 | remaining_string = _{ ( ANY ) + } 6 | end_of_command = _{ ("\r" | "\n") * ~ EOI } 7 | // space rule is buggy, check "pushabc" and "push abc" 8 | 9 | cmd_stop_head = { "quit" | "exit" | "stop" | "q" } 10 | stop_reason = { remaining_string } 11 | cmd_stop = _{ cmd_stop_head ~ ( space ~ stop_reason )? } 12 | cmd_list_head = { "list" | "l" } 13 | list_keyword = { nonspace_string } 14 | cmd_list = _{ cmd_list_head ~ ( space ~ list_keyword )? } 15 | cmd_push_head = { "push" | "msg" | "say" | "send" | "p" } 16 | sender_id = { nonspace_string } 17 | chan_id = { nonspace_string } 18 | msg = { remaining_string } 19 | cmd_push = _{ cmd_push_head ~ space ~ sender_id ~ space ~ chan_id ~ space ~ msg } 20 | cmd_huaji_head = { "huaji" } 21 | cmd_huaji = _{ cmd_huaji_head } 22 | 23 | command = _{ SOI ~ space ~ (cmd_stop | cmd_list | cmd_push | cmd_huaji) ? ~ space ~ end_of_command } 24 | -------------------------------------------------------------------------------- /src/easechat-nexus-rs/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | collections::{HashMap, VecDeque}, 3 | sync::{mpsc, Arc, RwLock}, 4 | thread, 5 | time::{Instant, Duration}, 6 | }; 7 | use pest_derive::Parser; 8 | use pest::Parser; 9 | 10 | #[derive(Parser)] 11 | #[grammar = "console_rule.pest"] 12 | struct NexusParser; 13 | 14 | #[derive(Clone)] 15 | struct Env { 16 | ep: Arc>>, 17 | chan: Arc>>>, // chan_id -> ep 18 | } 19 | 20 | impl Env { 21 | pub fn new() -> Self { 22 | Env { 23 | ep: Arc::new(RwLock::new(HashMap::new())), 24 | chan: Arc::new(RwLock::new(HashMap::new())) 25 | } 26 | } 27 | 28 | pub fn add_ep(&mut self, ep_id: String, sender: ws::Sender) { 29 | if let Ok(mut map) = self.ep.write() { 30 | map.insert(ep_id, sender); 31 | } 32 | } 33 | 34 | pub fn ep_reg_chan(&mut self, ep_id: String, chan_id: String, time_sec: u64, time_nanos: u64) -> Option { 35 | if let Some(sender) = self.ep.read().unwrap().get(&ep_id) { 36 | let expire = Instant::now() + Duration::from_secs(time_sec) + Duration::from_nanos(time_nanos); 37 | self.chan.write().unwrap().entry(chan_id).or_insert(HashMap::new()).insert(ep_id, (expire, sender.clone())); 38 | Some(expire) 39 | } else { 40 | None 41 | } 42 | } 43 | 44 | pub fn push_text(&mut self, src_ep_id: String, chan_id: String, text: String) -> ws::Result { 45 | let map = self.chan.read().unwrap(); 46 | let now = Instant::now(); 47 | let mut cnt = 0; 48 | if let Some(senders) = map.get(&chan_id) { 49 | for (ep_id, (valid_until, sender)) in senders.iter() { 50 | if valid_until >= &now { 51 | if ep_id != &src_ep_id { 52 | sender.send(format!("1r|{}|{}|{}|{}|{}|{}", src_ep_id.len(), src_ep_id, chan_id.len(), chan_id, text.len(), text))?; 53 | cnt += 1; 54 | } 55 | } 56 | // 这里不能填write,会死锁 57 | } 58 | } 59 | Ok(cnt) 60 | } 61 | 62 | pub fn remove_ep(&mut self, ep_id: String) { 63 | self.ep.write().unwrap().remove(&ep_id); 64 | for (_chan, map) in self.chan.write().unwrap().iter_mut() { 65 | map.retain(|inner_ep_id, _instant_sender| &ep_id != inner_ep_id); 66 | } 67 | } 68 | 69 | pub fn broadcast_and_shutdown(&mut self, code: ws::CloseCode, reason: String) -> ws::Result<()> { 70 | let mut ep = self.ep.write().unwrap(); 71 | let mut chan = self.chan.write().unwrap(); 72 | for sender in ep.values() { 73 | sender.close_with_reason(code, reason.clone())?; 74 | } 75 | ep.clear(); 76 | chan.clear(); 77 | Ok(()) 78 | } 79 | 80 | fn size_summary(&self) -> (usize, usize) { 81 | let ep_len = self.ep.read().unwrap().len(); 82 | let sub_len = self.chan.read().unwrap().len(); 83 | (ep_len, sub_len) 84 | } 85 | 86 | fn summary_by_keyword(&self, kw: &str) -> 87 | (Vec<(String, Instant)>, Vec<(String, Instant)>) 88 | // (by sender_id) chan_id => expire | (by chan_id) sender_id => expire 89 | { 90 | let map = self.chan.read().unwrap(); 91 | let mut ans_sender = Vec::new(); 92 | if let Some(ep_ins_map) = map.get(kw) { 93 | for (ep_id, (expire_at, _sender)) in ep_ins_map { 94 | ans_sender.push((ep_id.clone(), *expire_at)) 95 | } 96 | } 97 | let mut ans_chan = Vec::new(); 98 | for (chan_id, ep_ins_map) in map.iter() { 99 | for (ep_id, (expire_at, _sender)) in ep_ins_map { 100 | if ep_id == kw { 101 | ans_chan.push((chan_id.clone(), *expire_at)) 102 | } 103 | } 104 | } 105 | (ans_sender, ans_chan) 106 | } 107 | } 108 | 109 | struct MsgServiceFactory { 110 | log_tx: mpsc::Sender, 111 | msg_tx: mpsc::Sender, 112 | } 113 | 114 | #[derive(Clone)] 115 | struct MsgServiceHandler { 116 | log_tx: mpsc::Sender, 117 | msg_tx: mpsc::Sender, 118 | ws_sender: ws::Sender, 119 | ep_id: Option, 120 | } 121 | 122 | impl MsgServiceFactory { 123 | pub fn new(log_tx: mpsc::Sender, msg_tx: mpsc::Sender) -> Self { 124 | log_tx.send(LogSignal::ModuleStart(String::from("MSG-SERV"))).unwrap(); 125 | Self { log_tx, msg_tx } 126 | } 127 | } 128 | 129 | impl ws::Factory for MsgServiceFactory { 130 | type Handler = MsgServiceHandler; 131 | fn connection_made(&mut self, ws_sender: ws::Sender) -> Self::Handler { 132 | Self::Handler { 133 | ws_sender, 134 | log_tx: self.log_tx.clone(), 135 | msg_tx: self.msg_tx.clone(), 136 | ep_id: None, 137 | } 138 | } 139 | } 140 | 141 | impl ws::Handler for MsgServiceHandler { 142 | fn on_open(&mut self, shake: ws::Handshake) -> ws::Result<()> { 143 | if let Some(addr) = shake.remote_addr()? { 144 | self.log_tx.send(LogSignal::ConnectionOpen(addr.clone())).unwrap(); 145 | Ok(()) 146 | } else { 147 | self.ws_sender.close(ws::CloseCode::Status) 148 | } 149 | } 150 | 151 | fn on_close(&mut self, code: ws::CloseCode, reason: &str) { 152 | self.msg_tx.send(MsgSignal::EpLogout { ep_id: self.ep_id.clone(), code, reason: reason.to_string() }).unwrap(); 153 | } 154 | 155 | fn on_message(&mut self, msg: ws::Message) -> ws::Result<()> { 156 | if let ws::Message::Text(text) = msg { 157 | self.handle_message_signal(text.chars().collect()) 158 | } else { 159 | self.ws_sender.close_with_reason(ws::CloseCode::Unsupported, "Please input as string text") 160 | } 161 | } 162 | 163 | fn on_error(&mut self, err: ws::Error) { 164 | self.log_tx.send(LogSignal::Display(String::from("ERRORS"), format!("{:?}", err))).unwrap(); 165 | } 166 | } 167 | 168 | impl MsgServiceHandler { 169 | // message string format: version+type|data 170 | // data of text: len|chan_id|len|msg_str 171 | // data of chan: len|chan_id|u64|u32(duration sec/nanos since unix epoch) 172 | // 1h|16|eafc5479a7e9f012 173 | // 1t|7|c/lobby|10|helloworld 174 | // 1c|7|c/lobby|1548507103|2140083600 175 | // 1d|11|just logout 176 | #[inline] 177 | fn handle_message_signal(&mut self, mut text: VecDeque) -> ws::Result<()> { 178 | match text.pop_front() { 179 | Some('1') => self.handle_v1(text), 180 | _ => self.ws_sender.close_with_reason(ws::CloseCode::Protocol, "Protocol other than '1' is not supported") 181 | } 182 | } 183 | 184 | #[inline] 185 | fn handle_v1(&mut self, mut text: VecDeque) -> ws::Result<()> { 186 | match (text.pop_front(), text.pop_front()) { 187 | (Some('h'), Some('|')) => self.handle_v1_handshake(text), 188 | (Some('t'), Some('|')) => self.handle_v1_text(text), 189 | (Some('c'), Some('|')) => self.handle_v1_chan(text), 190 | (Some('d'), Some('|')) => self.handle_v1_disconnect(text), 191 | _ => self.ws_sender.close_with_reason(ws::CloseCode::Invalid, "Invalid message type: expected 'h', 't', 'c' or 'd'"), 192 | } 193 | } 194 | 195 | #[inline] 196 | fn read_number(text: &mut VecDeque) -> u64 { 197 | let mut cur = text.pop_front(); 198 | while let Some(c) = cur { 199 | if c.to_digit(10).is_some() { 200 | break; 201 | } 202 | cur = text.pop_front(); 203 | } 204 | let mut ans = 0; 205 | while let Some(c) = cur { 206 | if let Some(digit) = c.to_digit(10) { 207 | ans *= 10; 208 | ans += digit as u64; 209 | cur = text.pop_front(); 210 | } else { 211 | return ans; 212 | } 213 | }; 214 | return ans; 215 | } 216 | 217 | #[inline] 218 | fn read_string(text: &mut VecDeque) -> String { 219 | let cap = Self::read_number(text); 220 | let mut ans = String::with_capacity(cap as usize); 221 | for _i in 0..cap { 222 | if let Some(ch) = text.pop_front() { 223 | ans.push(ch) 224 | } 225 | } 226 | ans 227 | } 228 | 229 | // 16|eafc5479a7e9f012 230 | #[inline] 231 | fn handle_v1_handshake(&mut self, mut text: VecDeque) -> ws::Result<()> { 232 | let ep_id = Self::read_string(&mut text); 233 | self.ep_id = Some(ep_id.clone()); 234 | self.msg_tx.send(MsgSignal::EpIdentify { ep_id: ep_id.clone(), ws_sender: self.ws_sender.clone() }).unwrap(); 235 | Ok(()) 236 | } 237 | 238 | // 7|c/lobby|10|helloworld 239 | #[inline] 240 | fn handle_v1_text(&mut self, mut text: VecDeque) -> ws::Result<()> { 241 | if let Some(src_ep_id) = self.ep_id.clone() { 242 | let chan_id = Self::read_string(&mut text); 243 | let text = Self::read_string(&mut text); 244 | println!("{}, {}!", chan_id, text); 245 | self.msg_tx.send(MsgSignal::Text { src_ep_id, chan_id, text }).unwrap(); 246 | Ok(()) 247 | } else { 248 | self.ws_sender.close_with_reason(ws::CloseCode::Status, "Connection unidentified") 249 | } 250 | } 251 | 252 | // 7|c/lobby|1548507103|2140083600 253 | #[inline] 254 | fn handle_v1_chan(&mut self, mut text: VecDeque) -> ws::Result<()> { 255 | if let Some(src_ep_id) = self.ep_id.clone() { 256 | let chan_id = Self::read_string(&mut text); 257 | let valid_until_sec = Self::read_number(&mut text); 258 | let valid_until_nanos = Self::read_number(&mut text); 259 | self.msg_tx.send(MsgSignal::Chan { src_ep_id, chan_id, valid_until_sec, valid_until_nanos }).unwrap(); 260 | Ok(()) 261 | } else { 262 | self.ws_sender.close_with_reason(ws::CloseCode::Status, "Connection unidentified") 263 | } 264 | } 265 | 266 | // 11|just logout 267 | #[inline] 268 | fn handle_v1_disconnect(&mut self, mut text: VecDeque) -> ws::Result<()> { 269 | let code = ws::CloseCode::Normal; 270 | let reason = Self::read_string(&mut text); 271 | self.ws_sender.close_with_reason(code, reason) 272 | } 273 | } 274 | 275 | 276 | #[derive(Debug)] 277 | enum LogSignal { 278 | ModuleStart(String), 279 | ConnectionOpen(String), 280 | ConnectionIdentified(String), 281 | ConnectionClose(Option, ws::CloseCode, String), 282 | ChannelAdd(String, String, Instant), 283 | MessageSent(String, String, usize, String), 284 | Display(String, String), 285 | } 286 | 287 | enum MsgSignal { 288 | EpIdentify { 289 | ep_id: String, 290 | ws_sender: ws::Sender, 291 | }, 292 | Text { 293 | src_ep_id: String, 294 | chan_id: String, 295 | text: String, 296 | }, 297 | Chan { 298 | src_ep_id: String, 299 | chan_id: String, 300 | valid_until_sec: u64, 301 | valid_until_nanos: u64, 302 | }, 303 | EpLogout { 304 | ep_id: Option, 305 | code: ws::CloseCode, 306 | reason: String, 307 | }, 308 | Status { 309 | keyword: Option, 310 | }, 311 | ShutdownRequest { 312 | reason: String, 313 | }, 314 | } 315 | 316 | fn main() { 317 | let (log_tx, log_rx) = mpsc::channel(); 318 | let (msg_tx, msg_rx) = mpsc::channel(); 319 | let mut env = Env::new(); 320 | thread::spawn(move || { 321 | while let Ok(sig) = log_rx.recv() { 322 | use LogSignal::*; 323 | match sig { 324 | ModuleStart(meta) => 325 | println!("[Module {}] Started!", meta), 326 | ConnectionOpen(client_addr) => 327 | println!("[Addr {}] Connection open!", client_addr), 328 | ConnectionIdentified(ep_id) => 329 | println!("[EpID {}] Connection identified!", ep_id), 330 | ConnectionClose(addr, code, reason) => { 331 | if let Some(ep_id) = addr { 332 | println!("[EpID {}] Connection closed, Code:[{:?}], Reason:[{}]", ep_id, code, reason) 333 | } else { 334 | println!("[Unidentified] Connection closed, Code:[{:?}], Reason:[{}]", code, reason) 335 | } 336 | }, 337 | ChannelAdd(src_ep_id, chan_id, expire) => 338 | println!("[EpID {}] Registered new channel [{}], expire at {:?}", src_ep_id, chan_id, expire), 339 | MessageSent(src_ep_id, chan_id, ep_cnt, text) => 340 | println!("[EpID {}] Sent to {} [{} client(s) excluding self]: {}", src_ep_id, chan_id, ep_cnt, text), 341 | Display(module, string) => 342 | println!("[Module {}] {}", module, string), 343 | } 344 | } 345 | }); 346 | let log_tx1 = log_tx.clone(); 347 | thread::spawn(move || { 348 | while let Ok(sig) = msg_rx.recv() { 349 | use MsgSignal::*; 350 | match sig { 351 | EpIdentify { ep_id, ws_sender } => { 352 | env.add_ep(ep_id.clone(), ws_sender); 353 | log_tx1.send(LogSignal::ConnectionIdentified(ep_id)).unwrap(); 354 | }, 355 | EpLogout { ep_id, code, reason } => { 356 | if let Some(ep_id) = ep_id.clone() { 357 | env.remove_ep(ep_id); 358 | } 359 | log_tx1.send(LogSignal::ConnectionClose(ep_id, code, String::from(reason))).unwrap() 360 | }, 361 | Chan { src_ep_id, chan_id, valid_until_sec, valid_until_nanos } => { 362 | if let Some(expire) = env.ep_reg_chan(src_ep_id.clone(), chan_id.clone(), valid_until_sec, valid_until_nanos) { 363 | log_tx1.send(LogSignal::ChannelAdd(src_ep_id, chan_id, expire)).unwrap(); 364 | } 365 | }, 366 | Text { src_ep_id, chan_id, text } => { 367 | if let Ok(ep_cnt) = env.push_text(src_ep_id.clone(), chan_id.clone(), text.clone()) { 368 | log_tx1.send(LogSignal::MessageSent(src_ep_id, chan_id, ep_cnt, text)).unwrap(); 369 | } else { 370 | eprintln!("error!"); 371 | }; 372 | }, 373 | Status { keyword } => { 374 | if let Some(keyword) = keyword { 375 | let (ans_sender, ans_chan) = env.summary_by_keyword(&keyword); 376 | let mut out = String::new(); 377 | let now = Instant::now(); 378 | fn process_expire(expire: Instant, now: Instant) -> String { 379 | if expire > now { format!("expire at {:?}", expire - now) } 380 | else { "already expired".to_string() } 381 | } 382 | if ans_chan.len() == 0 && ans_sender.len() == 0 { 383 | out += &format!("No status found for keyword [{}].", keyword); 384 | } 385 | if ans_chan.len() > 0 { 386 | out += &format!("EpID [{}] listens {} channel(s):", keyword, ans_chan.len()); 387 | for (chan_id, expire) in ans_chan { 388 | out += &format!("\n\tchannel: [{}], {}", chan_id, process_expire(expire, now)); 389 | } 390 | } 391 | if ans_sender.len() > 0 { 392 | out += &format!("Channel [{}] is subscribed by {} client(s):", keyword, ans_sender.len()); 393 | for (sender_id, expire) in ans_sender { 394 | out += &format!("\n\tsender: [{}], {}", sender_id, process_expire(expire, now)); 395 | } 396 | } 397 | log_tx1.send(LogSignal::Display("STATUS".to_string(), out)).unwrap(); 398 | } else { 399 | let (ep_len, sub_len) = env.size_summary(); 400 | let out = format!("{} clients identified, {} channels active.", ep_len, sub_len); 401 | log_tx1.send(LogSignal::Display("STATUS".to_string(), out)).unwrap(); 402 | } 403 | }, 404 | ShutdownRequest { reason } => { 405 | println!("Shutting down with reason [{}]...", reason); 406 | env.broadcast_and_shutdown(ws::CloseCode::Normal, reason).unwrap(); 407 | std::process::exit(0) 408 | }, 409 | }; 410 | } 411 | }); 412 | let addr = std::env::args().nth(1).unwrap_or("0.0.0.0:6500".to_string()); 413 | let settings = ws::Settings { 414 | max_connections: 4096, // 最大连接数,按需增加,千万不要设置到无穷大 415 | queue_size: 16, // 每个连接的事件数最大值,按业务量调整 416 | ..Default::default() 417 | }; 418 | println!("{:?}", settings); 419 | let log_tx1 = log_tx.clone(); 420 | let msg_tx1 = msg_tx.clone(); 421 | thread::spawn(move || { 422 | let fac = MsgServiceFactory::new(log_tx1.clone(), msg_tx1); 423 | log_tx1.send(LogSignal::Display(String::from("SOCKET"), format!("Listening on {}", addr))).unwrap(); 424 | ws::Builder::new().with_settings(settings) 425 | .build(fac).unwrap() 426 | .listen(addr).unwrap() 427 | }); 428 | log_tx.send(LogSignal::ModuleStart(String::from("CMDLINE"))).unwrap(); 429 | loop { 430 | let mut buf = String::new(); 431 | std::io::stdin().read_line(&mut buf).unwrap(); 432 | match NexusParser::parse(Rule::command, &buf.trim()) { 433 | Ok(mut pairs) => match pairs.next().map(|p| p.as_rule()) { 434 | Some(Rule::cmd_stop_head) => { 435 | let reason = pairs.next().map(|p| p.as_str()).unwrap_or("server shutdown").to_string(); 436 | msg_tx.send(MsgSignal::ShutdownRequest{ reason }).unwrap() 437 | }, 438 | Some(Rule::cmd_list_head) => if let Some(keyword) = pairs.next() { 439 | let mut keyword = Some(keyword.as_str().to_string()); 440 | if Some("".to_string()) == keyword { keyword = None } 441 | msg_tx.send(MsgSignal::Status { keyword }).unwrap() 442 | }, 443 | Some(Rule::cmd_push_head) => if let (Some(sender), Some(chan), Some(msg)) 444 | = (pairs.next(), pairs.next(), pairs.next()) { 445 | let src_ep_id = sender.as_str().to_string(); 446 | let chan_id = chan.as_str().to_string(); 447 | let text = msg.as_str().to_string(); 448 | msg_tx.send(MsgSignal::Text { src_ep_id, chan_id, text }).unwrap(); 449 | }, 450 | Some(Rule::cmd_huaji_head) => { 451 | log_tx.send(LogSignal::Display("CMDLINE".to_string(), "huaji".to_string())).unwrap(); 452 | }, 453 | Some(Rule::EOI) => {}, 454 | _ => eprintln!("unreachable expression, this is a bug!") 455 | }, 456 | Err(e) => { 457 | eprintln!("err: {}", e); 458 | } 459 | } 460 | } 461 | } 462 | -------------------------------------------------------------------------------- /src/easechat-nexus-v2-rs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "easechat-nexus" 3 | version = "0.0.0" 4 | authors = ["luojia65 "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | ws = "0.7.9" 9 | -------------------------------------------------------------------------------- /src/easechat-nexus-v2-rs/src/adapt.rs: -------------------------------------------------------------------------------- 1 | use super::service; 2 | use std::collections::VecDeque; 3 | use std::sync::mpsc; 4 | 5 | pub(crate) struct WsFactoryAdapt { 6 | inner: F, 7 | sig_tx: mpsc::Sender, 8 | } 9 | 10 | impl WsFactoryAdapt { 11 | fn new(inner: F, sig_tx: mpsc::Sender) -> Self { 12 | Self { inner, sig_tx } 13 | } 14 | } 15 | 16 | impl ws::Factory for WsFactoryAdapt 17 | where 18 | F: super::Factory 19 | { 20 | type Handler = WsHandlerAdapt; 21 | 22 | fn connection_made(&mut self, sender: ws::Sender) -> Self::Handler { 23 | let inner = self.inner.connection_made(super::Sender { inner: sender.clone() }); 24 | WsHandlerAdapt { inner, ws_sender: sender, sig_tx: self.sig_tx.clone(), echat_id: None } 25 | } 26 | 27 | fn connection_lost(&mut self, handler: Self::Handler) { 28 | self.inner.connection_lost(handler.inner) 29 | } 30 | } 31 | 32 | pub struct WsHandlerAdapt { 33 | inner: H, 34 | ws_sender: ws::Sender, 35 | sig_tx: mpsc::Sender, 36 | echat_id: Option 37 | } 38 | 39 | impl ws::Handler for WsHandlerAdapt 40 | where 41 | H: super::Handler 42 | { 43 | fn on_open(&mut self, shake: ws::Handshake) -> ws::Result<()> { 44 | self.inner.on_open(super::Handshake { inner: shake }); 45 | Ok(()) 46 | } 47 | 48 | fn on_close(&mut self, _code: ws::CloseCode, _reason: &str) { 49 | self.inner.on_close(); 50 | } 51 | 52 | fn on_message(&mut self, msg: ws::Message) -> ws::Result<()> { 53 | if let ws::Message::Text(text) = msg { 54 | self.handle_message_signal(text.chars().collect()) 55 | } else { 56 | self.ws_sender.close_with_reason(ws::CloseCode::Unsupported, "Please send string message") 57 | } 58 | } 59 | } 60 | 61 | #[inline] 62 | fn read_number(text: &mut VecDeque) -> u64 { 63 | let mut cur = text.pop_front(); 64 | while let Some(c) = cur { 65 | if c.to_digit(10).is_some() { 66 | break; 67 | } 68 | cur = text.pop_front(); 69 | } 70 | let mut ans = 0; 71 | while let Some(c) = cur { 72 | if let Some(digit) = c.to_digit(10) { 73 | ans *= 10; 74 | ans += digit as u64; 75 | cur = text.pop_front(); 76 | } else { 77 | return ans; 78 | } 79 | }; 80 | return ans; 81 | } 82 | 83 | #[inline] 84 | fn read_string(text: &mut VecDeque) -> String { 85 | let cap = read_number(text); 86 | let mut ans = String::with_capacity(cap as usize); 87 | for _i in 0..cap { 88 | if let Some(ch) = text.pop_front() { 89 | ans.push(ch) 90 | } 91 | } 92 | ans 93 | } 94 | 95 | impl WsHandlerAdapt { 96 | #[inline] 97 | fn handle_message_signal(&mut self, mut text: VecDeque) -> ws::Result<()> { 98 | match text.pop_front() { 99 | Some('1') => self.handle_v1(text), 100 | _ => self.ws_sender.close_with_reason(ws::CloseCode::Protocol, "Protocol not supported") 101 | } 102 | } 103 | 104 | #[inline] 105 | fn handle_v1(&mut self, mut text: VecDeque) -> ws::Result<()> { 106 | match (text.pop_front(), text.pop_front()) { 107 | (Some('h'), Some('|')) => self.handle_v1_handshake(text), 108 | (Some('c'), Some('|')) => self.handle_v1_listen_channel(text), 109 | (Some('t'), Some('|')) => self.handle_v2_transmit_message(text), 110 | _ => self.ws_sender.close_with_reason(ws::CloseCode::Invalid, "Invalid message type"), 111 | } 112 | } 113 | 114 | #[inline] 115 | fn handle_v1_handshake(&mut self, mut text: VecDeque) -> ws::Result<()> { 116 | let id = read_string(&mut text); 117 | self.echat_id = Some(id.clone()); 118 | self.sig_tx.send(service::Signal::Register { id: id.clone(), sender: super::Sender::new(self.ws_sender.clone()) }).unwrap(); 119 | Ok(()) 120 | } 121 | 122 | #[inline] 123 | fn handle_v1_listen_channel(&mut self, mut text: VecDeque) -> ws::Result<()> { 124 | if let Some(src_id) = self.echat_id.clone() { 125 | let chan_id = read_string(&mut text); 126 | let valid_sec = read_number(&mut text); 127 | let valid_nanos = read_number(&mut text); 128 | self.sig_tx.send(service::Signal::Listen { src_id: src_id.clone(), target_id: chan_id.clone(), valid_sec, valid_nanos }).unwrap(); 129 | Ok(()) 130 | } else { 131 | self.ws_sender.close_with_reason(ws::CloseCode::Status, "Connection unidentified") 132 | } 133 | } 134 | 135 | #[inline] 136 | fn handle_v2_transmit_message(&mut self, mut text: VecDeque) -> ws::Result<()> { 137 | if let Some(src_id) = self.echat_id.clone() { 138 | let chan_id = read_string(&mut text); 139 | let msg = read_string(&mut text); 140 | self.sig_tx.send(service::Signal::Push { src_id: src_id.clone(), dest_id: chan_id.clone(), msg: msg.clone() }).unwrap(); 141 | Ok(()) 142 | } else { 143 | self.ws_sender.close_with_reason(ws::CloseCode::Status, "Connection unidentified") 144 | } 145 | } 146 | 147 | } 148 | 149 | 150 | 151 | -------------------------------------------------------------------------------- /src/easechat-nexus-v2-rs/src/lib.rs: -------------------------------------------------------------------------------- 1 | mod adapt; 2 | mod service; 3 | 4 | pub struct EaseChat 5 | where 6 | F: Factory 7 | { 8 | socket: ws::WebSocket>, 9 | srv: service::Service, 10 | } 11 | 12 | impl EaseChat 13 | where 14 | F: Factory 15 | {} 16 | 17 | 18 | pub trait Factory { 19 | type Handler: Handler; 20 | 21 | fn connection_made(&mut self, _: Sender) -> Self::Handler; 22 | 23 | #[inline] 24 | fn client_connected(&mut self, ws: Sender) -> Self::Handler { 25 | self.connection_made(ws) 26 | } 27 | 28 | #[inline] 29 | fn server_connected(&mut self, ws: Sender) -> Self::Handler { 30 | self.connection_made(ws) 31 | } 32 | 33 | fn connection_lost(&mut self, _: Self::Handler) {} 34 | } 35 | 36 | pub trait Handler { 37 | fn on_open(&mut self, _: Handshake) {} 38 | 39 | fn on_close(&mut self) {} 40 | 41 | fn on_handshake(&mut self, _id: String) {} 42 | 43 | fn on_listen_channel(&mut self, _target_id: String) {} 44 | 45 | fn on_push_message(&mut self, _dest_id: String, _msg: String) {} 46 | 47 | fn on_accept_message(&mut self, _src_id: String, _msg: String) {} 48 | } 49 | 50 | #[derive(Debug)] 51 | pub struct Handshake { 52 | inner: ws::Handshake, 53 | } 54 | 55 | #[derive(Clone)] 56 | pub struct Sender { 57 | inner: ws::Sender, 58 | } 59 | 60 | impl Sender { 61 | fn new(inner: ws::Sender) -> Self { 62 | Self { inner } 63 | } 64 | 65 | pub fn send_msg(&self, src_id: &str, dest_id: &str, msg: &str) -> ws::Result<()> { 66 | let string = format!("1r|{}|{}|{}|{}|{}|{}", src_id.len(), src_id, dest_id.len(), dest_id, msg.len(), msg); 67 | self.inner.send(string) 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/easechat-nexus-v2-rs/src/service.rs: -------------------------------------------------------------------------------- 1 | use super::Sender; 2 | use std::collections::HashMap; 3 | use std::sync::{Arc, RwLock}; 4 | use std::time::{Instant, Duration}; 5 | 6 | #[derive(Clone)] 7 | pub(crate) struct Service { 8 | id_to_sender: Arc>>, 9 | listen: Arc>>>, 10 | } 11 | 12 | impl Service { 13 | pub fn register_client(&mut self, id: String, sender: Sender) { 14 | self.id_to_sender.write().unwrap().insert(id, sender); 15 | } 16 | 17 | pub fn listen_channel(&mut self, src_id: String, target_id: String, valid_sec: u64, valid_nanos: u64) 18 | -> Option 19 | { 20 | self.id_to_sender.read().unwrap().get(&src_id).map(|sender| { 21 | let expire = Instant::now() + Duration::from_secs(valid_sec) + Duration::from_nanos(valid_nanos); 22 | self.listen.write().unwrap().entry(target_id).or_insert(HashMap::new()) 23 | .insert(src_id, (expire, sender.clone())); 24 | expire 25 | }) 26 | } 27 | 28 | pub fn push_message(&mut self, src_id: String, dest_id: String, msg: String) 29 | -> ws::Result 30 | { 31 | let map = self.listen.read().unwrap(); 32 | let now = Instant::now(); 33 | let mut cnt = 0; 34 | if let Some(senders) = map.get(&dest_id) { 35 | for (ep_id, (valid_until, sender)) in senders.iter() { 36 | if valid_until >= &now { 37 | if ep_id != &src_id { 38 | sender.send_msg(&src_id, &dest_id, &msg)?; 39 | cnt += 1 40 | } 41 | } else { 42 | if let Some(mp) = self.listen.write().unwrap().get_mut(&dest_id) { 43 | mp.remove(ep_id); 44 | } 45 | } 46 | } 47 | } 48 | Ok(cnt) 49 | } 50 | 51 | pub fn unregister_client(&mut self, src_id: String) { 52 | self.id_to_sender.write().unwrap().remove(&src_id); 53 | for (_chan, map) in self.listen.write().unwrap().iter_mut() { 54 | map.retain(|inner_ep_id, _instant_sender| &src_id != inner_ep_id); 55 | } 56 | } 57 | } 58 | 59 | pub enum Signal { 60 | Register { 61 | id: String, 62 | sender: Sender, 63 | }, 64 | Listen { 65 | src_id: String, 66 | target_id: String, 67 | valid_sec: u64, 68 | valid_nanos: u64, 69 | }, 70 | Push { 71 | src_id: String, 72 | dest_id: String, 73 | msg: String, 74 | }, 75 | Accept { 76 | src_id: String, 77 | msg: String, 78 | }, 79 | Unregister { 80 | src_id: String, 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/easechat-record-rs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "easechat-record" 3 | version = "0.0.0" 4 | authors = ["luojia65 "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | chrono = "0.4" 9 | ws = "0.7.9" 10 | clap = "2" 11 | rusqlite = { version = "0.16", features = ["chrono"] } 12 | -------------------------------------------------------------------------------- /src/easechat-record-rs/examples/simple-mem-db.rs: -------------------------------------------------------------------------------- 1 | use rusqlite::types::ToSql; 2 | use rusqlite::{Connection, NO_PARAMS}; 3 | use chrono::{DateTime, Local}; 4 | 5 | fn main() { 6 | let conn = Connection::open_in_memory().unwrap(); 7 | 8 | conn.execute( 9 | "CREATE TABLE IF NOT EXISTS msg ( 10 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 11 | time TEXT NOT NULL, 12 | channel TEXT NOT NULL, 13 | text TEXT NOT NULL 14 | )", 15 | NO_PARAMS, 16 | ).unwrap(); 17 | 18 | conn.execute( 19 | "INSERT INTO msg (time, channel, text) values (?1, ?2, ?3)", 20 | &[&Local::now() as &dyn ToSql, &"c:123", &"d:456"] 21 | ).unwrap(); 22 | 23 | let mut stmt = conn 24 | .prepare("SELECT id, time, channel, text FROM msg") 25 | .unwrap(); 26 | let mut iter = stmt 27 | .query(NO_PARAMS) 28 | .unwrap(); 29 | 30 | while let Some(Ok(row)) = iter.next() { 31 | let id: u32 = row.get("id"); 32 | let time: DateTime = row.get("time"); 33 | let channel: String = row.get("channel"); 34 | let text: String = row.get("text"); 35 | println!("Found row {:?}", (id, time, channel, text)); 36 | } 37 | 38 | /* 39 | 40 | let conn = Connection::open_in_memory().unwrap(); 41 | 42 | conn.execute( 43 | "CREATE TABLE person ( 44 | id INTEGER PRIMARY KEY, 45 | name TEXT NOT NULL, 46 | time_created TEXT NOT NULL, 47 | data BLOB 48 | )", 49 | NO_PARAMS, 50 | ).unwrap(); 51 | let me = Person { 52 | id: 0, 53 | name: "Steven".to_string(), 54 | time_created: time::get_time(), 55 | data: None, 56 | }; 57 | conn.execute( 58 | "INSERT INTO person (name, time_created, data) 59 | VALUES (?1, ?2, ?3)", 60 | &[&me.name as &ToSql, &me.time_created, &me.data], 61 | ).unwrap(); 62 | 63 | let mut stmt = conn 64 | .prepare("SELECT id, name, time_created, data FROM person") 65 | .unwrap(); 66 | let person_iter = stmt 67 | .query_map(NO_PARAMS, |row| Person { 68 | id: row.get(0), 69 | name: row.get(1), 70 | time_created: row.get(2), 71 | data: row.get(3), 72 | }).unwrap(); 73 | 74 | for person in person_iter { 75 | println!("Found person {:?}", person.unwrap()); 76 | } 77 | */ 78 | } -------------------------------------------------------------------------------- /src/easechat-record-rs/src/main.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate clap; 3 | 4 | use std::thread; 5 | use rusqlite::{NO_PARAMS, Connection}; 6 | use clap::App; 7 | 8 | fn main() { 9 | let matches = clap_app!(easechat_record => 10 | (version: "0.0.0") 11 | (author: "Luo Jia ") 12 | (about: "Connect to easechat server and record messages on some channels") 13 | (@arg HOSTNAME: +required "Sets the host ip address of server") 14 | (@arg PORT: -p --port +takes_value "Sets the port of server, default to 6500") 15 | (@arg SQLITE_PATH: --save-sqlite +takes_value "Sets a SQLite file path for storage") 16 | ).get_matches(); 17 | let conn = Connection::open_in_memory().unwrap(); 18 | conn.execute( 19 | "CREATE TABLE IF NOT EXISTS msg ( 20 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 21 | time TEXT NOT NULL, 22 | channel TEXT NOT NULL, 23 | text TEXT NOT NULL 24 | )", 25 | NO_PARAMS, 26 | ).unwrap(); 27 | 28 | // let url = "localhost:6500"; 29 | 30 | // thread::spawn(move || { 31 | // ws::connect(url, |out| { 32 | // out.send("Hello WebSocket").unwrap(); 33 | // move |msg| { 34 | // println!("Got message: {}", msg); 35 | // out.close(CloseCode::Normal) 36 | // } 37 | // }).unwrap(); 38 | // }); 39 | } 40 | -------------------------------------------------------------------------------- /start.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | cargo run --bin ease_chat_nexus 3 | --------------------------------------------------------------------------------