All Projects β†’ DarthPestilane β†’ easytcp

DarthPestilane / easytcp

Licence: MIT license
✨ πŸš€ EasyTCP is a light-weight TCP framework written in Go (Golang), built with message router. EasyTCP helps you build a TCP server easily fast and less painful.

Programming Languages

go
31211 projects - #10 most used programming language
Makefile
30231 projects
shell
77523 projects

Projects that are alternatives of or similar to easytcp

Oksocket
An blocking socket client for Android applications.
Stars: ✭ 2,359 (+467.07%)
Mutual labels:  tcp, tcp-server
tcp server client
A thin and simple C++ TCP client server
Stars: ✭ 124 (-70.19%)
Mutual labels:  tcp, tcp-server
neteng-roadmap
Network Engineering at Scale Roadmap/Landscape
Stars: ✭ 53 (-87.26%)
Mutual labels:  router, tcp
React Native Tcp Socket
React Native TCP socket API for Android, iOS & macOS with client SSL/TLS support
Stars: ✭ 112 (-73.08%)
Mutual labels:  tcp, tcp-server
tcp-net
Build tcp applications in a stable and elegant way
Stars: ✭ 42 (-89.9%)
Mutual labels:  tcp, tcp-server
Simpletcp
A minimal non-blocking TCP server written for Python 3.
Stars: ✭ 162 (-61.06%)
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 (-95.67%)
Mutual labels:  tcp, tcp-server
Packetsender
Network utility for sending / receiving TCP, UDP, SSL
Stars: ✭ 1,349 (+224.28%)
Mutual labels:  tcp, tcp-server
SuperSimpleTcp
Simple wrapper for TCP client and server in C# with SSL support
Stars: ✭ 263 (-36.78%)
Mutual labels:  tcp, tcp-server
AsyncTcpClient
An asynchronous variant of TcpClient and TcpListener for .NET Standard.
Stars: ✭ 125 (-69.95%)
Mutual labels:  tcp, tcp-server
Esp8266 Wifi Uart Bridge
Transparent WiFi (TCP, UDP) to UART Bridge, in AP or STATION mode
Stars: ✭ 107 (-74.28%)
Mutual labels:  tcp, tcp-server
ctsTraffic
ctsTraffic is a highly scalable client/server networking tool giving detailed performance and reliability analytics
Stars: ✭ 125 (-69.95%)
Mutual labels:  tcp, tcp-server
Deta cache
ηΌ“ε­˜cacheζœεŠ‘ε™¨
Stars: ✭ 106 (-74.52%)
Mutual labels:  tcp, tcp-server
Simplenet
An easy-to-use, event-driven, asynchronous network application framework compiled with Java 11.
Stars: ✭ 164 (-60.58%)
Mutual labels:  tcp, tcp-server
Simpletcp
Simple wrapper for TCP client and server in C# with SSL support
Stars: ✭ 99 (-76.2%)
Mutual labels:  tcp, tcp-server
http-connection-lifecycle
Complete and detailed explanation of HTTP connection lifecycle
Stars: ✭ 43 (-89.66%)
Mutual labels:  router, tcp
Godsharp.socket
An easy-to-use .NET socket server and client.
Stars: ✭ 35 (-91.59%)
Mutual labels:  tcp, tcp-server
Easytcp
Simple framework for TCP clients and servers. Focused on performance and usability.
Stars: ✭ 60 (-85.58%)
Mutual labels:  tcp, tcp-server
QTcpSocket
A simple Qt client-server TCP architecture to transfer data between peers
Stars: ✭ 62 (-85.1%)
Mutual labels:  tcp, tcp-server
network
exomia/network is a wrapper library around System.Socket for easy and fast TCP/UDP client & server communication.
Stars: ✭ 18 (-95.67%)
Mutual labels:  tcp, tcp-server

EasyTCP

gh-action Go Report codecov Go Reference Mentioned in Awesome Go

$ ./start

[EASYTCP] Message-Route Table:
+------------+-----------------------+
| Message ID |     Route Handler     |
+------------+-----------------------+
|       1000 | path/to/handler.Func1 |
+------------+-----------------------+
|       1002 | path/to/handler.Func2 |
+------------+-----------------------+
[EASYTCP] Serving at: tcp://[::]:10001

Introduction

EasyTCP is a light-weight and less painful TCP server framework written in Go (Golang) based on the standard net package.

✨ Features:

  • Non-invasive design
  • Pipelined middlewares for route handler
  • Customizable message packer and codec, and logger
  • Handy functions to handle request data and send response
  • Common hooks

EasyTCP helps you build a TCP server easily and fast.

This package has been tested in go1.16 ~ go1.18 on the latest Linux, Macos and Windows.

Install

Use the below Go command to install EasyTCP.

$ go get -u github.com/DarthPestilane/easytcp

Note: EasyTCP uses Go Modules to manage dependencies.

Quick start

package main

import (
    "fmt"
    "github.com/DarthPestilane/easytcp"
    "github.com/DarthPestilane/easytcp/message"
)

func main() {
    // Create a new server with options.
    s := easytcp.NewServer(&easytcp.ServerOption{
        Packer: easytcp.NewDefaultPacker(), // use default packer
        Codec:  nil,                        // don't use codec
    })

    // Register a route with message's ID.
    // The `DefaultPacker` treats id as int,
    // so when we add routes or return response, we should use int.
    s.AddRoute(1001, func(c easytcp.Context) {
        // acquire request
        req := c.Request()

        // do things...
        fmt.Printf("[server] request received | id: %d; size: %d; data: %s\n", req.ID(), len(req.Data()), req.Data())

        // set response
        c.SetResponseMessage(easytcp.NewMessage(1002, []byte("copy that")))
    })

    // Set custom logger (optional).
    easytcp.SetLogger(lg)

    // Add global middlewares (optional).
    s.Use(recoverMiddleware)

    // Set hooks (optional).
    s.OnSessionCreate = func(session easytcp.Session) {...}
    s.OnSessionClose = func(session easytcp.Session) {...}

    // Set not-found route handler (optional).
    s.NotFoundHandler(handler)

    // Listen and serve.
    if err := s.Serve(":5896"); err != nil && err != server.ErrServerStopped {
        fmt.Println("serve error: ", err.Error())
    }
}

If we setup with the codec

// Create a new server with options.
s := easytcp.NewServer(&easytcp.ServerOption{
    Packer: easytcp.NewDefaultPacker(), // use default packer
    Codec:  &easytcp.JsonCodec{},       // use JsonCodec
})

// Register a route with message's ID.
// The `DefaultPacker` treats id as int,
// so when we add routes or return response, we should use int.
s.AddRoute(1001, func(c easytcp.Context) {
    // decode request data and bind to `reqData`
    var reqData map[string]interface{}
    if err := c.Bind(&reqData); err != nil {
        // handle err
    }

    // do things...
    respId := 1002
    respData := map[string]interface{}{
        "success": true,
        "feeling": "Great!",
    }

    // encode response data and set to `c`
    if err := c.SetResponse(respId, respData); err != nil {
        // handle err
    }
})

Above is the server side example. There are client and more detailed examples including:

in examples/tcp.

Benchmark

go test -bench=. -run=none -benchmem -benchtime=250000x
goos: darwin
goarch: amd64
pkg: github.com/DarthPestilane/easytcp
cpu: Intel(R) Core(TM) i5-8279U CPU @ 2.40GHz
Benchmark_NoHandler-8                     250000              4667 ns/op              84 B/op          2 allocs/op
Benchmark_OneHandler-8                    250000              4351 ns/op              82 B/op          2 allocs/op
Benchmark_DefaultPacker_Pack-8            250000                33.57 ns/op           16 B/op          1 allocs/op
Benchmark_DefaultPacker_Unpack-8          250000               104.4 ns/op            96 B/op          3 allocs/op

since easytcp is built on the top of golang net library, the benchmark of networks does not make much sense.

Architecture

accepting connection:

+------------+    +-------------------+    +----------------+
|            |    |                   |    |                |
|            |    |                   |    |                |
| tcp server |--->| accept connection |--->| create session |
|            |    |                   |    |                |
|            |    |                   |    |                |
+------------+    +-------------------+    +----------------+

in session:

+------------------+    +-----------------------+    +----------------------------------+
| read connection  |--->| unpack packet payload |--->|                                  |
+------------------+    +-----------------------+    |                                  |
                                                     | router (middlewares and handler) |
+------------------+    +-----------------------+    |                                  |
| write connection |<---| pack packet payload   |<---|                                  |
+------------------+    +-----------------------+    +----------------------------------+

in route handler:

+----------------------------+    +------------+
| codec decode request data  |--->|            |
+----------------------------+    |            |
                                  | user logic |
+----------------------------+    |            |
| codec encode response data |<---|            |
+----------------------------+    +------------+

Conception

Routing

EasyTCP considers every message has a ID segment to distinguish one another. A message will be routed, according to it's id, to the handler through middlewares.

request flow:

+----------+    +--------------+    +--------------+    +---------+
| request  |--->|              |--->|              |--->|         |
+----------+    |              |    |              |    |         |
                | middleware 1 |    | middleware 2 |    | handler |
+----------+    |              |    |              |    |         |
| response |<---|              |<---|              |<---|         |
+----------+    +--------------+    +--------------+    +---------+

Register a route

s.AddRoute(reqID, func(c easytcp.Context) {
    // acquire request
    req := c.Request()

    // do things...
    fmt.Printf("[server] request received | id: %d; size: %d; data: %s\n", req.ID(), len(req.Data()), req.Data())

    // set response
    c.SetResponseMessage(easytcp.NewMessage(respID, []byte("copy that")))
})

Using middleware

// register global middlewares.
// global middlewares are prior than per-route middlewares, they will be invoked first
s.Use(recoverMiddleware, logMiddleware, ...)

// register middlewares for one route
s.AddRoute(reqID, handler, middleware1, middleware2)

// a middleware looks like:
var exampleMiddleware easytcp.MiddlewareFunc = func(next easytcp.HandlerFunc) easytcp.HandlerFunc {
    return func(c easytcp.Context) {
        // do things before...
        next(c)
        // do things after...
    }
}

Packer

A packer is to pack and unpack packets' payload. We can set the Packer when creating the server.

s := easytcp.NewServer(&easytcp.ServerOption{
    Packer: new(MyPacker), // this is optional, the default one is DefaultPacker
})

We can set our own Packer or EasyTCP uses DefaultPacker.

The DefaultPacker considers packet's payload as a Size(4)|ID(4)|Data(n) format. Size only represents the length of Data instead of the whole payload length

This may not covery some particular cases, but fortunately, we can create our own Packer.

// CustomPacker is a custom packer, implements Packer interafce.
// Treats Packet format as `size(2)id(2)data(n)`
type CustomPacker struct{}

func (p *CustomPacker) bytesOrder() binary.ByteOrder {
    return binary.BigEndian
}

func (p *CustomPacker) Pack(msg *easytcp.Message) ([]byte, error) {
    size := len(msg.Data()) // only the size of data.
    buffer := make([]byte, 2+2+size)
    p.bytesOrder().PutUint16(buffer[:2], uint16(size))
    p.bytesOrder().PutUint16(buffer[2:4], msg.ID().(uint16))
    copy(buffer[4:], msg.Data())
    return buffer, nil
}

func (p *CustomPacker) Unpack(reader io.Reader) (*easytcp.Message, error) {
    headerBuffer := make([]byte, 2+2)
    if _, err := io.ReadFull(reader, headerBuffer); err != nil {
        return nil, fmt.Errorf("read size and id err: %s", err)
    }
    size := p.bytesOrder().Uint16(headerBuffer[:2])
    id := p.bytesOrder().Uint16(headerBuffer[2:])

    data := make([]byte, size)
    if _, err := io.ReadFull(reader, data); err != nil {
        return nil, fmt.Errorf("read data err: %s", err)
    }

    // since msg.ID is type of uint16, we need to use uint16 as well when adding routes.
    // eg: server.AddRoute(uint16(123), ...)
    msg := easytcp.NewMessage(id, data)
    msg.Set("theWholeLength", 2+2+size) // we can set our custom kv data here.
    // c.Request().Get("theWholeLength")  // and get them in route handler.
    return msg, nil
}

And see more custom packers:

Codec

A Codec is to encode and decode message data. The Codec is optional, EasyTCP won't encode or decode message data if the Codec is not set.

We can set Codec when creating the server.

s := easytcp.NewServer(&easytcp.ServerOption{
    Codec: &easytcp.JsonCodec{}, // this is optional. The JsonCodec is a built-in codec
})

Since we set the codec, we may want to decode the request data in route handler.

s.AddRoute(reqID, func(c easytcp.Context) {
    var reqData map[string]interface{}
    if err := c.Bind(&reqData); err != nil { // here we decode message data and bind to reqData
        // handle error...
    }
    req := c.Request()
    fmt.Printf("[server] request received | id: %d; size: %d; data-decoded: %+v\n", req.ID(), len(req.Data()), reqData())
    respData := map[string]string{"key": "value"}
    if err := c.SetResponse(respID, respData); err != nil {
        // handle error...
    }
})

Codec's encoding will be invoked before message packed, and decoding should be invoked in the route handler which is after message unpacked.

JSON Codec

JsonCodec is an EasyTCP's built-in codec, which uses encoding/json as the default implementation. Can be changed by build from other tags.

jsoniter :

go build -tags=jsoniter .

Protobuf Codec

ProtobufCodec is an EasyTCP's built-in codec, which uses google.golang.org/protobuf as the implementation.

Msgpack Codec

MsgpackCodec is an EasyTCP's built-in codec, which uses github.com/vmihailenco/msgpack as the implementation.

Contribute

Check out a new branch for the job, and make sure github action passed.

Use issues for everything

  • For a small change, just send a PR.
  • For bigger changes open an issue for discussion before sending a PR.
  • PR should have:
    • Test case
    • Documentation
    • Example (If it makes sense)
  • You can also contribute by:
    • Reporting issues
    • Suggesting new features or enhancements
    • Improve/fix documentation

Stargazers over time

Stargazers over time

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].