bsp

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 8, 2026 License: MIT Imports: 8 Imported by: 0

README

Binary Socket Protocol

A simple unstructured fixed-length full-duplex messaging protocol, implemented in Go. Similar to Websockets, but without the bloat.

Examples

Server
package main

import (
	"bsp"
	"log"
)

// Server

func main() {

	server, err := bsp.Listen("127.0.0.1:12001")

	if err != nil {
		panic(err)
	}

	// Server connection acceptance loop
	for {
		socket, err := server.Accept()

		if err != nil {
			// Errors may occur if e.g. a client
			// that connects does not perform the handshake.
			continue
		}

		go handleSocket(socket)
	}

}

func handleSocket(socket *bsp.Socket) {
	msg, err := socket.Receive()

	if err != nil {
		return
	}

	log.Println(msg.Content())

	// simply echo it back
	socket.Send(msg)
} 
Client
package main

import (
	"bsp"
	"log"
	"time"
)

func main() {
	socket, err := bsp.Dial("127.0.0.1:12001")

	if err != nil {
		panic(err)
	}

	go sender(socket)
	go receiver(socket)

	// Await for the connection to close.
	// You could also implement your own closing mechanism.
	<-socket.Done
}

func sender(socket *bsp.Socket) {
	// Send a message every second
	for {
		err := socket.Send(bsp.NewMessage([]byte("Hello world!")))

		if err != nil {
			return
		}

		time.Sleep(time.Second * 2)
	}
}

func receiver(socket *bsp.Socket) {
	for {
		msg, err := socket.Receive()

		if err != nil {
			return
		}

		log.Printf("Received a message: %s \n", msg.Content())
	}
}

Documentation

Index

Constants

View Source
const (
	DefaultKeepaliveInterval = time.Second * 10
	DefaultReadTimeout       = time.Minute
	DefaultWriteTimeout      = time.Minute
)
View Source
const ProtocolId = 0xF2

Variables

This section is empty.

Functions

This section is empty.

Types

type Listener

type Listener struct {
	// contains filtered or unexported fields
}

func Listen

func Listen(addr string) (Listener, error)

Listen starts listening for incoming connections.

func (Listener) Accept

func (l Listener) Accept() (*Socket, error)

func (Listener) Close

func (l Listener) Close() error

type Message

type Message struct {
	// contains filtered or unexported fields
}

func NewMessage

func NewMessage(data []byte) Message

func (Message) Content

func (d Message) Content() []byte

type ProtocolMessage

type ProtocolMessage struct {
	Id   ProtocolMessageID
	Data []byte
}

ProtocolMessage represents a single message sent over the wire.

func NewProtocolMessage

func NewProtocolMessage(id ProtocolMessageID, data []byte) ProtocolMessage

func (ProtocolMessage) Serialize

func (p ProtocolMessage) Serialize() []byte

Serialize the message into a byte slice.

type ProtocolMessageBuffer

type ProtocolMessageBuffer struct {
	// contains filtered or unexported fields
}

ProtocolMessageBuffer

The protocol message buffer is used to buffer incoming messages. Given that TCP is a stream protocol, incoming bytes are buffered until we have a full message. Once a full message is received, it is parsed and emitted on the message channel of the buffer.

func NewProtocolMessageBuffer

func NewProtocolMessageBuffer() *ProtocolMessageBuffer

func (*ProtocolMessageBuffer) Add

func (pmb *ProtocolMessageBuffer) Add(b []byte, processNow bool) error

Add bytes to the buffer. The flag processNow indicates whether the buffer should be processed immediately. If false, the buffer will be only processed by calling ProcessBytes() manually. A possible use case is to accumulate multiple messages into a single buffer before processing them, or to have a concurrent message buffer that processes messages in the background. If true will process the bytes immediately. Note that this will panic if ProcessBytes() is called concurrently.

func (*ProtocolMessageBuffer) ProcessBytes

func (pmb *ProtocolMessageBuffer) ProcessBytes() error

ProcessBytes processes all buffered bytes. This function will block until all bytes have been processed. It will panic if called concurrently.

type ProtocolMessageBufferState

type ProtocolMessageBufferState byte

ProtocolMessageBufferState represents the state of the message buffer, used to parse incoming messages.

const (
	PMBNeutral ProtocolMessageBufferState = iota
	PMBId
	PMBDataLength
	PMBData
)

type ProtocolMessageID

type ProtocolMessageID byte
const (
	IdHandshake    ProtocolMessageID = 0x00
	IdHandshakeAck ProtocolMessageID = 0x01
	IdKeepAlive    ProtocolMessageID = 0x02
	IdDataMessage  ProtocolMessageID = 0x03
	IdClose        ProtocolMessageID = 0x04
)

type ProtocolSession

type ProtocolSession struct {
	// contains filtered or unexported fields
}

type SessionSide

type SessionSide bool

SessionSide represents the side of the connection. Used in the handshake and in keepalive messages.

const (
	Server SessionSide = true
	Client SessionSide = false
)

type SessionState

type SessionState byte

SessionState represents the state of a protocol session, primarily used in the handshake.

const (
	SessionStateNew           SessionState = iota // Initial state, no handshake sent yet
	SessionStateHandshakeSent                     // Handshake sent, waiting for handshake ack
	SessionStateConnected                         // Server: Handshake ack sent, client: Handshake ack received
	SessionStateClosed                            // Connection closed
)

type Socket

type Socket struct {
	Done chan struct{}
	// contains filtered or unexported fields
}

Socket represents a BSP connection socket.

func Dial

func Dial(addr string) (*Socket, error)

Dial connects to a server at the given address.

func NewSocket

func NewSocket(conn net.Conn, side SessionSide) *Socket

func (*Socket) Close

func (s *Socket) Close(err error) error

Close the socket

func (*Socket) Receive

func (s *Socket) Receive() (Message, error)

func (*Socket) Send

func (s *Socket) Send(m Message) error

Send a message over the socket. Use NewMessage to create a Message.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL