goetty

package module
v2.0.3-0...-26c9a2f Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2023 License: Apache-2.0 Imports: 19 Imported by: 11

README

goetty

Goetty is a framework to help you build socket application.

Example

server

package example

import (
	"log"

	"github.com/fagongzi/goetty"
	"github.com/fagongzi/goetty/codec/simple"
)

// EchoServer echo server
type EchoServer struct {
	addr string
	app  goetty.NetApplication
}

// NewEchoServer create new server
func NewEchoServer(addr string) *EchoServer {
	svr := &EchoServer{}
	encoder, decoder := simple.NewStringCodec()
	app, err := goetty.NewTCPApplication(addr, svr.handle,
		goetty.WithAppSessionOptions(goetty.WithCodec(encoder, decoder)))
	if err != nil {
		log.Panicf("start server failed with %+v", err)
	}

	return &EchoServer{
		addr: addr,
		app:  app,
	}
}

// Start start
func (s *EchoServer) Start() error {
	return s.Start()
}

// Stop stop
func (s *EchoServer) Stop() error {
	return s.Stop()
}

func (s *EchoServer) handle(session goetty.IOSession, msg interface{}, received uint64) error {
	log.Printf("received %+v from %s, already received %d msgs",
		msg,
		session.RemoteAddr(),
		received)
	return session.WriteAndFlush(msg)
}

client

package example

import (
	"log"
	"time"

	"github.com/fagongzi/goetty"
	"github.com/fagongzi/goetty/codec/simple"
)

// EchoClient echo client
type EchoClient struct {
	serverAddr string
	conn       goetty.IOSession
}

// NewEchoClient new client
func NewEchoClient(serverAddr string) (*EchoClient, error) {
	c := &EchoClient{
		serverAddr: serverAddr,
	}

	encoder, decoder := simple.NewStringCodec()
	c.conn = goetty.NewIOSession(goetty.WithCodec(encoder, decoder))
	_, err := c.conn.Connect(serverAddr, time.Second*3)
	return c, err
}

// SendMsg send msg to server
func (c *EchoClient) SendMsg(msg string) error {
	return c.conn.WriteAndFlush(msg)
}

// ReadLoop read loop
func (c *EchoClient) ReadLoop() error {
	// start loop to read msg from server
	for {
		msg, err := c.conn.Read() // if you want set a read deadline, you can use 'WithTimeout option'
		if err != nil {
			log.Printf("read failed with %+v", err)
			return err
		}

		log.Printf("received %+v", msg)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrIllegalState illegal state error
	ErrIllegalState = errors.New("illegal state")
	// ErrDisableConnect disable to connect
	ErrDisableConnect = errors.New("io session is disable to connect")
)

Functions

This section is empty.

Types

type AppOption

type AppOption func(*server)

AppOption application option

func WithAppHandleSessionFunc

func WithAppHandleSessionFunc(value func(IOSession) error) AppOption

WithAppHandleSessionFunc set the app handle session funcpl

func WithAppLogger

func WithAppLogger(logger *zap.Logger) AppOption

WithAppLogger set logger for application

func WithAppSessionAware

func WithAppSessionAware(value IOSessionAware) AppOption

WithAppSessionBucketSize set the app session aware

func WithAppSessionBucketSize

func WithAppSessionBucketSize(value uint64) AppOption

WithAppSessionBucketSize set the number of maps to store session

func WithAppSessionOptions

func WithAppSessionOptions(options ...Option) AppOption

WithAppSessionOptions set options to create new connection

func WithAppTLS

func WithAppTLS(tlsCfg *tls.Config) AppOption

WithAppTLS set tls config for application

func WithAppTLSFromCertAndKey

func WithAppTLSFromCertAndKey(
	certFile string,
	keyFile string,
	caFile string,
	insecureSkipVerify bool) AppOption

WithAppTLSFromKeys set tls config from cert and key files for application

type BufferedIOSession

type BufferedIOSession interface {
	// BufferedConn returns a wrapped net.Conn that read from IOSession's in-buffer first
	BufferedConn() net.Conn
	// InBuf returns inbuf which used to decode bytes to message
	InBuf() *buf.ByteBuf
}

BufferedIOSession is a IOSession that can read from the in-buffer first

type IOSession

type IOSession interface {
	// ID session id
	ID() uint64
	// Connect connect to address, only used at client-side
	Connect(addr string, timeout time.Duration) error
	// Connected returns true if connection is ok
	Connected() bool
	// Disconnect disconnect the connection
	Disconnect() error
	// Close close the session, the read and write buffer will closed, and cannot Connect
	// again. IOSession reference count minus 1.
	Close() error
	// Ref for IOSessions, held by several goroutines, several references are needed. Each
	// concurrent process holding an IOSession can Close the IOSession and release the resource
	// when the reference count reaches 0.
	Ref()
	// Read read packet from connection
	Read(option ReadOptions) (any, error)
	// Write encodes the msg into a []byte into the buffer according to the codec.Encode.
	// If flush is set to flase, the data will not be written to the underlying socket.
	Write(msg any, options WriteOptions) error
	// Flush flush the out buffer
	Flush(timeout time.Duration) error
	// RemoteAddress returns remote address, include ip and port
	RemoteAddress() string
	// RawConn return raw tcp conn, RawConn should only be used to access the underlying
	// attributes of the tcp conn, e.g. set keepalive attributes. Read from RawConn directly
	// may lose data since the bytes might have been copied to the InBuf.
	// To perform read/write operation on the underlying tcp conn, use BufferedConn instead.
	RawConn() net.Conn
	// UseConn use the specified conn to handle reads and writes. Note that conn reads and
	// writes cannot be handled in other goroutines until UseConn is called.
	UseConn(net.Conn)
	// OutBuf returns bytebuf which used to encode message into bytes
	OutBuf() *buf.ByteBuf
}

IOSession internally holds a raw net.Conn on which to provide read and write operations

func NewIOSession

func NewIOSession(opts ...Option) IOSession

NewIOSession create a new io session

type IOSessionAware

type IOSessionAware interface {
	// Created session created
	Created(IOSession)
	//Closed session closed
	Closed(IOSession)
}

IOSessionAware io session aware

type NetApplication

type NetApplication interface {
	// Start start the transport server
	Start() error
	// Stop stop the transport server
	Stop() error
	// GetSession get session
	GetSession(uint64) (IOSession, error)
}

NetApplication is a network based application

func NewApplication

func NewApplication(address string, handleFunc func(IOSession, any, uint64) error, opts ...AppOption) (NetApplication, error)

NewApplication returns a application

func NewApplicationWithListenAddress

func NewApplicationWithListenAddress(addresses []string, handleFunc func(IOSession, any, uint64) error, opts ...AppOption) (NetApplication, error)

NewApplicationWithListenAddress create a net application with listen multi addresses

func NewApplicationWithListeners

func NewApplicationWithListeners(listeners []net.Listener, handleFunc func(IOSession, any, uint64) error, opts ...AppOption) (NetApplication, error)

NewApplicationWithListener returns a net application with listener

type Option

type Option func(*baseIO)

Option option to create IOSession

func WithSessionAllocator

func WithSessionAllocator(allocator buf.Allocator) Option

WithSessionAllocator set mem allocator to build in and out ByteBuf

func WithSessionAware

func WithSessionAware(value IOSessionAware) Option

WithSessionAware set IOSession's session aware

func WithSessionCodec

func WithSessionCodec(codec codec.Codec) Option

WithSessionCodec set codec for IOSession

func WithSessionConn

func WithSessionConn(id uint64, conn net.Conn) Option

WithSessionConn set IOSession's net.Conn

func WithSessionDisableAutoResetInBuffer

func WithSessionDisableAutoResetInBuffer() Option

WithSessionDisableAutoResetInBuffer set disable auto reset in buffer. If disabled, the application must reset in buffer in the read loop, otherwise there will be a memory leak.

func WithSessionDisableCompactAfterGrow

func WithSessionDisableCompactAfterGrow() Option

WithSessionDisableCompactAfterGrow set Set whether the buffer should be compressed, if it is, it will reset the reader and writer index. Default is true.

func WithSessionLogger

func WithSessionLogger(logger *zap.Logger) Option

WithSessionLogger set logger for IOSession

func WithSessionRWBUfferSize

func WithSessionRWBUfferSize(read, write int) Option

WithSessionRWBUfferSize set read/write buf size for IOSession

func WithSessionReleaseMsgFunc

func WithSessionReleaseMsgFunc(value func(any)) Option

WithSessionReleaseMsgFunc set a func to release message once the message encode into the write buf

func WithSessionTLS

func WithSessionTLS(tlsConfig *tls.Config) Option

WithSessionTLS set tls for client

func WithSessionTLSFromCertAndKeys

func WithSessionTLSFromCertAndKeys(certFile, keyFile, caFile string, insecureSkipVerify bool) Option

WithSessionTLSFromCertAndKeys set tls for client

type Proxy

type Proxy interface {
	// Start start the proxy
	Start() error
	// Stop stop the proxy
	Stop() error
	// AddUpStream add upstream
	AddUpStream(address string, connectTimeout time.Duration)
}

Proxy simple reverse proxy

func NewProxy

func NewProxy(address string, logger *zap.Logger) Proxy

NewProxy returns a simple tcp proxy

type ReadOptions

type ReadOptions struct {
	// Timeout deadline for read
	Timeout time.Duration
}

ReadOptions read options

type WriteOptions

type WriteOptions struct {
	// Timeout deadline for write
	Timeout time.Duration
	// Flush flush data to net.Conn
	Flush bool
}

WriteOptions write options

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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