aboutsummaryrefslogtreecommitdiff
path: root/README.md
blob: 9a53b26e09a0f35a6dca130308d3f72937fa4bf3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# binproto

Simple binary protocol with multiplexing support.

[![Go Reference](https://pkg.go.dev/badge/github.com/tetsuo/binproto.svg)](https://pkg.go.dev/github.com/tetsuo/binproto)

## Install

```sh
go get github.com/tetsuo/binproto
```

## Usage

To start exchanging messages with binproto, simply wrap a `net.Conn` with a `binproto.Conn` instance.

Then, once connected, use `ReadMessage()` to read incoming messages and `Send()` to send new ones over the network.

#### Server

```go
package main

import (
    "fmt"
    "log"
    "net"

    "github.com/tetsuo/binproto"
)

func main() {
    s := &server{}
    if err := s.serve("tcp", ":4242"); err != nil {
        log.Fatal(err)
    }
}

type server struct {
    listener net.Listener
}

// handle manages an individual client connection.
// It reads each message, prints its content, and responds with a simple reply.
func (s *server) handle(conn net.Conn) {
    defer conn.Close()
    c := binproto.NewConn(conn)
    msg := &binproto.Message{}
    for {
        err := c.ReadMessage(msg)
        if err != nil {
            fmt.Printf("error: %v", err)
            return
        }
        fmt.Printf("%d %d %s\n", msg.ID, msg.Channel, msg.Data)

        _, err = c.Send(binproto.NewMessage(112, 5, []byte("hello")))
        if err != nil {
            log.Fatal(err)
        }
    }
}

// serve starts listening for incoming TCP connections.
// For each new connection, it launches handle in a separate goroutine.
func (s *server) serve(network, address string) error {
    l, err := net.Listen(network, address)
    if err != nil {
        return err
    }
    s.listener = l

    for {
        if s.listener == nil {
            break
        }
        c, err := l.Accept()
        if err != nil {
            continue
        }
        go s.handle(c)
    }
    return nil
}

// close cleanly shuts down the server listener.
func (s *server) close() error {
    err := s.listener.Close()
    s.listener = nil
    return err
}
```

#### Client

```go
package main

import (
    "fmt"
    "log"

    "github.com/tetsuo/binproto"
)

func main() {
    // Connect to the server on localhost:4242 using binproto
    c, err := binproto.Dial("tcp", ":4242")
    if err != nil {
        log.Fatal(err)
    }

    // Start a goroutine to read and print incoming messages from the server
    go func() {
        msg := &binproto.Message{}
        for {
            err := c.ReadMessage(msg)
            if err != nil {
                log.Fatal(err)
                return
            }

            fmt.Printf("%d %d %s\n", msg.ID, msg.Channel, msg.Data)
        }
    }()

    // Send a message to the server: ID=42, Channel=3, Data="hi"
    _, err = c.Send(binproto.NewMessage(42, 3, []byte("hi")))
    if err != nil {
        log.Fatal(err)
    }

    select {} // Keeps main from exiting immediately
}
```

## Message structure

Every message is encoded with a 64-bit header: a length prefix followed by a channel ID and type.

```
╔──────────────────────────────────────────────╗
│ length | channel ID × channel type │ payload │
╚──────────────────────────────────────────────╝
           └─ 60-bits   └─ 4-bits
```

* **Channel ID (first 60 bits)**: Identifies the specific channel for the message.
* **Channel Type (last 4 bits)**: Specifies the type of data in the message.

## Encryption

binproto itself doesn't provide encryption. However, encryption can be added by using Go libraries that act as drop-in replacements for `net`, for example by wrapping your connections with an implementation of the [NOISE protocol](http://www.noiseprotocol.org/).

## Configure buffer size

binproto operates with a default internal buffer size of 4096 bytes, meaning data is processed as long as it meets or exceeds this buffer size, which is an effective default for many applications. This value can be adjusted to better suit protocols that use larger or smaller data chunks, optimizing performance as needed.

> 📄 **For more details, see the API documentation at [pkg.go.dev](https://pkg.go.dev/github.com/tetsuo/binproto).**