All Projects → eyasliu → cs

eyasliu / cs

Licence: MIT License
开箱即用的基于命令的消息处理框架,让 websocket 和 tcp 开发就像 http 那样简单

Programming Languages

go
31211 projects - #10 most used programming language
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to cs

Socketify
Raw TCP and UDP Sockets API on Desktop Browsers
Stars: ✭ 67 (+252.63%)
Mutual labels:  tcp, websocket-server, tcp-server
Swoft
🚀 PHP Microservice Full Coroutine Framework
Stars: ✭ 5,420 (+28426.32%)
Mutual labels:  websocket-server, tcp-server, http-server
Cppserver
Ultra fast and low latency asynchronous socket server & client C++ library with support TCP, SSL, UDP, HTTP, HTTPS, WebSocket protocols and 10K connections problem solution
Stars: ✭ 528 (+2678.95%)
Mutual labels:  websocket-server, tcp-server, http-server
Netcoreserver
Ultra fast and low latency asynchronous socket server & client C# .NET Core library with support TCP, SSL, UDP, HTTP, HTTPS, WebSocket protocols and 10K connections problem solution
Stars: ✭ 799 (+4105.26%)
Mutual labels:  websocket-server, tcp-server, http-server
Mgx
🌈 A high performance network framework written in c++ (support tcp and http)
Stars: ✭ 15 (-21.05%)
Mutual labels:  tcp, tcp-server, http-server
Mongols
C++ high performance networking with TCP/UDP/RESP/HTTP/WebSocket protocols
Stars: ✭ 250 (+1215.79%)
Mutual labels:  websocket-server, tcp-server, http-server
Iodine
iodine - HTTP / WebSockets Server for Ruby with Pub/Sub support
Stars: ✭ 720 (+3689.47%)
Mutual labels:  websocket-server, sse, http-server
node-jsonrpc2
JSON-RPC 2.0 server and client library, with HTTP (with Websocket support) and TCP endpoints
Stars: ✭ 103 (+442.11%)
Mutual labels:  tcp, websocket-server, http-server
Beetlex
high performance dotnet core socket tcp communication components, support TLS, HTTP, HTTPS, WebSocket, RPC, Redis protocols, custom protocols and 1M connections problem solution
Stars: ✭ 802 (+4121.05%)
Mutual labels:  tcp, websocket-server, http-server
tcp server client
A thin and simple C++ TCP client server
Stars: ✭ 124 (+552.63%)
Mutual labels:  tcp, tcp-server
QTcpSocket
A simple Qt client-server TCP architecture to transfer data between peers
Stars: ✭ 62 (+226.32%)
Mutual labels:  tcp, tcp-server
SuperSimpleTcp
Simple wrapper for TCP client and server in C# with SSL support
Stars: ✭ 263 (+1284.21%)
Mutual labels:  tcp, tcp-server
go-eventserver
A socket server which reads events from an event source and forwards them to the user clients when appropriate
Stars: ✭ 18 (-5.26%)
Mutual labels:  tcp, tcp-server
rockgo
A developing game server framework,based on Entity Component System(ECS).
Stars: ✭ 617 (+3147.37%)
Mutual labels:  websocket-server, tcp-server
AsyncTcpClient
An asynchronous variant of TcpClient and TcpListener for .NET Standard.
Stars: ✭ 125 (+557.89%)
Mutual labels:  tcp, tcp-server
go-sse
Fully featured, spec-compliant HTML5 server-sent events library
Stars: ✭ 165 (+768.42%)
Mutual labels:  sse, http-server
machat
An open source chat server implemented in Go
Stars: ✭ 73 (+284.21%)
Mutual labels:  websocket-server, tcp-server
network
exomia/network is a wrapper library around System.Socket for easy and fast TCP/UDP client & server communication.
Stars: ✭ 18 (-5.26%)
Mutual labels:  tcp, tcp-server
Oksocket
An blocking socket client for Android applications.
Stars: ✭ 2,359 (+12315.79%)
Mutual labels:  tcp, tcp-server
tcp-net
Build tcp applications in a stable and elegant way
Stars: ✭ 42 (+121.05%)
Mutual labels:  tcp, tcp-server

Command Service

Build Status Go Doc Code Coverage License

开箱即用的基于命令的消息处理框架,让 websocket 和 tcp 开发就像 http 那样简单

使用示例

package main
import (
  "net/http"
  "github.com/eyasliu/cs"
  "github.com/eyasliu/cs/xwebsocket"
)

func main() {
  // 初始化 websocket
  ws := xwebsocket.New()
  http.Handle("/ws", ws)

  srv := ws.Srv()
  srv.Use(cs.AccessLogger("MYSRV")). // 打印请求响应日志
            Use(cs.Recover()) // 统一错误处理,消化 panic 错误

  srv.Handle("register", func(c *cs.Context) {
    // 定义请求数据
    var body struct {
      UID  int    `p:"uid" v:"required"`
      Name string `p:"name" v:"required|min:4#必需指定名称|名称长度必需大于4位"`
    }
    // 解析请求数据
    if err := c.Parse(&body); err != nil {
      c.Err(err, 401)
      return
    }
    // 设置会话状态数据
    c.Set("uid", body.UID)
    c.Set("name", body.Name)

    // 响应消息
    c.OK(map[string]interface{}{
      "timestamp": time.Now().Unix(),
    })

    // 给所有连接广播消息
    c.Broadcast(&cs.Response{
      Cmd:  "someone_online",
      Data: body,
    })

    // 往当前连接主动推送消息
    c.Push(&cs.Response{
      Cmd:  "welcome",
      Data: "welcome to register my server",
    })

    // 遍历所有在线会话,获取其他会话的状态,并往指定会话推送消息
    for _, sid := range c.GetAllSID() {
      if c.Srv.GetState(sid, "uid") != nil {
        c.Srv.Push(sid, &cs.Response{
          Cmd:  "firend_online",
          Data: "your firend is online",
        })
      }
    }
  })

  // 分组
  group := srv.Group(func(c *cs.Context) {
    // 过滤指定请求
    if _, ok := c.Get("uid").(int); !ok {
      c.Err(errors.New("unregister session"), 101)
      return
    }
    c.Next()
  })

  group.Handle("userinfo", func(c *cs.Context) {
    uid := c.Get("uid").(int) // 中间件已处理过,可大胆断言
    c.OK(map[string]interface{}{
      "uid": uid,
    })
  })
  go srv.Run()

  http.ListenAndServe(":8080", nil)
}

适配器

用在 websocket

import (
  "net/http"
  "github.com/eyasliu/cs/xwebsocket"
)

func main() {
  ws := xwebsocket.New()
  http.Handler("/ws", ws.Handler)
  srv := ws.Srv(ws)
  go srv.Run()

  http.ListenAndServe(":8080", nil)
}

用在 TCP,使用内置默认协议

import (
  "github.com/eyasliu/cs/xtcp"
)

func main() {
  server := xtcp.New("127.0.0.1:8520")
  srv, err := server.Srv()
  if err != nil {
    panic(err)
  }

  srv.Run() // 阻塞运行
}

用在 HTTP,支持请求响应,支持服务器主动推送

import (
  "net/http"
  "github.com/eyasliu/cs"
  "github.com/eyasliu/cs/xhttp"
)

func main() {
  server := xhttp.New()
  http.Handle("/cmd", server)
  http.HandleFunc("/cmd2", server.Handler)
  srv := server.Srv()
  go http.ListenAndServe(":8080", nil)
	
  srv.Run()
}

多个适配器混用,让 websocket, tcp, http 共用同一套逻辑

import (
  "net/http"
  "github.com/eyasliu/cs"
  "github.com/eyasliu/cs/xhttp"
  "github.com/eyasliu/cs/xwebsocket"
  "github.com/eyasliu/cs/xtcp"
)

func main() {
  // http adapter
  server := xhttp.New()
  http.Handle("/cmd", server)
  http.HandleFunc("/cmd2", server.Handler)
  
  // websocket adapter
  ws := xwebsocket.New()
  http.Handle("/ws", server)

  // tcp adapter
  tcp := xtcp.New()

  // boot srv
  go tcp.Run()
  go http.ListenAndServe(":8080", nil)

  srv := cs.New(server, ws, tcp)
  srv.Run() // 阻塞运行
}
$ curl -XPOST -H"Content-Type:application/json" --data '{"cmd":"register", "data":{"uid": 101, "name": "eyasliu"}}' http://localhost:8080/cmd
{"cmd":"register","data":{"timestamp": 1610960488}}

实现过程

在开发 websocket 和 tcp 的时候,对于长连接的消息处理都需要手动处理,并没有类似于 http 的路由那么方便,于是就想要实现一个可以处理该类消息的工具。

在长连接的开发中,经常遇到的一些问题:

  1. 每个连接会话在连接后都需要注册,以标识该连接的用途
  2. 每个请求都需要处理,并且保证一定有响应
  3. 往连接主动推送消息
  4. 给所有连接广播消息
  5. 消息处理的代码不够优雅,太多 switch case 等样板代码
  6. 请求的数据解析不好写

实现方案:

在 websocket 和 tcp 中,每个连接都抽象成一个字符串 SID, 即 Session ID, cs 只负责处理消息,不处理连接的任何状态,与连接和状态相关的操作全都以 interface 定义好,给各种工具去实现

API

GoDoc

License

cs is released under the MIT License.

(c) 2020-2021 Eyas Liu [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].