p2p

package module
v1.2.7 Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2022 License: GPL-3.0 Imports: 12 Imported by: 4

README

Golang TCP simple client and server

Import

import "github.com/leprosus/golang-p2p"

Create new TCP

tcp := p2p.NewTCP("localhost", 8080)

Server example

package main

import (
	"context"
	"fmt"
	"log"

	p2p "github.com/leprosus/golang-p2p"
)

func main() {
	tcp := p2p.NewTCP("localhost", 8080)
	settings := p2p.NewServerSettings()

	server := p2p.NewServer(tcp, settings)
	defer func() {
		err := server.Close()
		if err != nil {
			log.Panicln(err)
		}
	}()

	var c uint
	server.SetBytesHandle("counter", func(ctx context.Context, req []byte) (res []byte, err error) {
		fmt.Println(">", string(req))

		c++
		res = []byte(fmt.Sprintf("buy %d", c))

		return
	})

	err := server.Serve()
	if err != nil {
		log.Panicln(err)
	}
}

Client example

package main

import (
	"fmt"
	"log"

	p2p "github.com/leprosus/golang-p2p"
)

func main() {
	tcp := p2p.NewTCP("localhost", 8080)
	settings := p2p.NewClientSettings()

	client := p2p.NewClient(tcp, settings)

	for i := 0; i < 10; i++ {
		res, err := client.SendBytes("counter", []byte(fmt.Sprintf("hello %d", i+1)))
		if err != nil {
			log.Panicln(err)
		}

		fmt.Println("<", string(res))
	}
}

Running

If you run the server and the client separately then you see:

  • in the server stdout:
> hello 1
counter: addr (127.0.0.1:54014), read (344 µs), handle (26 µs), write (97 µs), total (468 µs)
> hello 2
counter: addr (127.0.0.1:54015), read (263 µs), handle (19 µs), write (50 µs), total (333 µs)
> hello 3
counter: addr (127.0.0.1:54016), read (310 µs), handle (44 µs), write (152 µs), total (507 µs)
> hello 4
counter: addr (127.0.0.1:54017), read (143 µs), handle (12 µs), write (48 µs), total (204 µs)
> hello 5
counter: addr (127.0.0.1:54018), read (118 µs), handle (12 µs), write (38 µs), total (169 µs)
> hello 6
counter: addr (127.0.0.1:54019), read (154 µs), handle (16 µs), write (51 µs), total (222 µs)
> hello 7
counter: addr (127.0.0.1:54020), read (133 µs), handle (9 µs), write (47 µs), total (190 µs)
> hello 8
counter: addr (127.0.0.1:54021), read (167 µs), handle (18 µs), write (48 µs), total (234 µs)
> hello 9
counter: addr (127.0.0.1:54022), read (212 µs), handle (20 µs), write (69 µs), total (302 µs)
> hello 10
counter: addr (127.0.0.1:54023), read (226 µs), handle (25 µs), write (47 µs), total (299 µs)
  • in the client stdout:
counter: addr (127.0.0.1:8080), write (216 µs), read (470 µs), total (687 µs)
< buy 1
counter: addr (127.0.0.1:8080), write (108 µs), read (321 µs), total (430 µs)
< buy 2
counter: addr (127.0.0.1:8080), write (151 µs), read (699 µs), total (851 µs)
< buy 3
counter: addr (127.0.0.1:8080), write (61 µs), read (295 µs), total (356 µs)
< buy 4
counter: addr (127.0.0.1:8080), write (56 µs), read (246 µs), total (303 µs)
< buy 5
counter: addr (127.0.0.1:8080), write (58 µs), read (300 µs), total (358 µs)
< buy 6
counter: addr (127.0.0.1:8080), write (55 µs), read (267 µs), total (322 µs)
< buy 7
counter: addr (127.0.0.1:8080), write (59 µs), read (327 µs), total (387 µs)
< buy 8
counter: addr (127.0.0.1:8080), write (78 µs), read (354 µs), total (432 µs)
< buy 9
counter: addr (127.0.0.1:8080), write (97 µs), read (361 µs), total (459 µs)
< buy 10
  • logging

All lines that start from counter (it is a topic for the communication) are logging in StdOut.

If you want to reassign this logger you need to implement your own with the following interface:

type Logger interface {
	Info(msg string)
	Warn(msg string)
	Error(msg string)
}

and set it up in your server or client implementation this way:

settings.SetLogger(yourLogger)

List all methods

TCP Initialization
  • p2p.NewTCP(host, port) (tcp TCP) - creates TCP connection
Server settings initialization
  • p2p.NewServerSettings() (stg) - creates a new server's settings
  • stg.SetLogger(l) - reassigns server's logger
  • stg.SetConnTimeout(dur) - sets connection timout
  • stg.SetHandleTimeout(dur) - sets handle timout
  • stg.SetBodyLimit(limit) - sets max body size for reading
Server
  • p2p.NewServer(tcp, stg) - creates a new server
  • srv.SetContext(ctx) - sets context
  • srv.SetBytesHandle(topic, handler) - sets a bytes handler that processes all request with defined topic
  • srv.SetObjectHandle(topic, handler) - sets an object handler that processes all request with defined topic
  • srv.Serve() (err) - starts to serve
  • srv.Close() (err) - stops and closes the server
Client settings initialization
  • p2p.NewClientSettings() (stg) - creates a new server's settings
  • stg.SetLogger(l) - reassigns server's logger
  • stg.SetConnTimeout(dur) - sets connection timout
  • stg.SetBodyLimit(limit) - sets max body size for writing
  • stg.SetRetry(retries, delay) - sets retry parameters
Client
  • NewClient(tcp, stg) (clt) - creates a new client
  • clt.SendBytes(topic, req) (res, err) - sends bytes to a server by the topic
  • clt.SendObject(topic, req) (res, err) - sends object to a server by the topic

Documentation

Index

Constants

View Source
const (
	DefaultConnTimeout   = 250 * time.Millisecond
	DefaultHandleTimeout = 250 * time.Millisecond
)
View Source
const (
	DefaultRetries      = 3
	DefaultDelayTimeout = 50 * time.Millisecond
)
View Source
const DefaultBodyLimit = 1024

Variables

View Source
var (
	UnsupportedTopic      = errors.New("unsupported topic")
	ConnectionError       = errors.New("connection error")
	PresetConnectionError = errors.New("preset connection error")
)

Functions

func Decode added in v1.2.5

func Decode(bs []byte) (val interface{}, err error)

func Encode added in v1.2.5

func Encode(val interface{}) (bs []byte, err error)

func MustDecode added in v1.2.5

func MustDecode(bs []byte) (val interface{})

func MustEncode added in v1.2.5

func MustEncode(val interface{}) (bs []byte)

func NewStdLogger added in v1.2.0

func NewStdLogger() (l *stdLogger)

Types

type BytesHandler added in v1.2.5

type BytesHandler func(ctx context.Context, req []byte) (res []byte, err error)

type Client added in v1.2.0

type Client struct {
	TCP
	ClientSettings
	// contains filtered or unexported fields
}

func NewClient added in v1.2.0

func NewClient(tcp TCP, stg ClientSettings) (c *Client)

func (*Client) SendBytes added in v1.2.5

func (c *Client) SendBytes(topic string, req []byte) (res []byte, err error)

func (*Client) SendObject added in v1.2.5

func (c *Client) SendObject(topic string, req interface{}) (res interface{}, err error)

type ClientSettings added in v1.2.0

type ClientSettings struct {
	Limiter
	Retry
	Logger
}

func NewClientSettings added in v1.2.0

func NewClientSettings() (stg ClientSettings)

func (*ClientSettings) SetBodyLimit added in v1.2.2

func (stg *ClientSettings) SetBodyLimit(limit uint)

func (*ClientSettings) SetConnTimeout added in v1.2.0

func (stg *ClientSettings) SetConnTimeout(dur time.Duration)

func (*ClientSettings) SetLogger added in v1.2.0

func (stg *ClientSettings) SetLogger(l Logger)

func (*ClientSettings) SetRetry added in v1.2.0

func (stg *ClientSettings) SetRetry(retries uint, delay time.Duration)

type Conn added in v1.2.0

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

type HandlerType added in v1.2.5

type HandlerType uint
const (
	BytesHandlerType HandlerType = iota
	ObjectHandlerType
)

type Limiter added in v1.2.0

type Limiter struct {
	Timeout
	// contains filtered or unexported fields
}

type Logger added in v1.2.0

type Logger interface {
	Info(msg string)
	Warn(msg string)
	Error(msg string)
}

type Message added in v1.2.0

type Message struct {
	Topic   string
	Content []byte
	Error   error
}

type Metrics added in v1.2.0

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

type ObjectHandler added in v1.2.5

type ObjectHandler func(ctx context.Context, req interface{}) (res interface{}, err error)

type Retry added in v1.2.0

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

type Server added in v1.2.0

type Server struct {
	TCP
	ServerSettings
	// contains filtered or unexported fields
}

func NewServer added in v1.2.0

func NewServer(tcp TCP, stg ServerSettings) (s *Server)

func (*Server) Close added in v1.2.0

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

func (*Server) Serve added in v1.2.0

func (s *Server) Serve() (err error)

func (*Server) SetBytesHandle added in v1.2.6

func (s *Server) SetBytesHandle(topic string, bh BytesHandler)

func (*Server) SetContext added in v1.2.4

func (s *Server) SetContext(ctx context.Context)

func (*Server) SetObjectHandle added in v1.2.6

func (s *Server) SetObjectHandle(topic string, oh ObjectHandler)

type ServerSettings added in v1.2.0

type ServerSettings struct {
	Limiter
	Logger
}

func NewServerSettings added in v1.2.0

func NewServerSettings() (stg ServerSettings)

func (*ServerSettings) SetBodyLimit added in v1.2.2

func (stg *ServerSettings) SetBodyLimit(limit uint)

func (*ServerSettings) SetConnTimeout added in v1.2.0

func (stg *ServerSettings) SetConnTimeout(dur time.Duration)

func (*ServerSettings) SetHandleTimeout added in v1.2.0

func (stg *ServerSettings) SetHandleTimeout(dur time.Duration)

func (*ServerSettings) SetLogger added in v1.2.0

func (stg *ServerSettings) SetLogger(l Logger)

type TCP

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

func NewTCP

func NewTCP(host string, port uint) (tcp TCP)

type Timeout added in v1.2.0

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

Jump to

Keyboard shortcuts

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