netty

package module
v1.6.5 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2024 License: Apache-2.0 Imports: 15 Imported by: 24

README

GO-NETTY

GoDoc license-Apache 2 Go Report Card Build Status Coverage Status

中文介绍

Introduction

go-netty is heavily inspired by netty

Feature

  • Extensible transport support, default support TCP, UDP, QUIC, KCP, Websocket
  • Extensible codec support
  • Based on responsibility chain model
  • Zero-dependency

Documentation

Examples

Quick Start

package main

import (
	"fmt"
	"strings"

	"github.com/go-netty/go-netty"
	"github.com/go-netty/go-netty/codec/format"
	"github.com/go-netty/go-netty/codec/frame"
)

func main() {
	// child pipeline initializer
	var childInitializer = func(channel netty.Channel) {
		channel.Pipeline().
			// the maximum allowable packet length is 128 bytes,use \n to split, strip delimiter
			AddLast(frame.DelimiterCodec(128, "\n", true)).
			// convert to string
			AddLast(format.TextCodec()).
			// LoggerHandler, print connected/disconnected event and received messages
			AddLast(LoggerHandler{}).
			// UpperHandler (string to upper case)
			AddLast(UpperHandler{})
	}

	// create bootstrap & listening & accepting
	netty.NewBootstrap(netty.WithChildInitializer(childInitializer)).
		Listen(":9527").Sync()
}

type LoggerHandler struct {}

func (LoggerHandler) HandleActive(ctx netty.ActiveContext) {
	fmt.Println("go-netty:", "->", "active:", ctx.Channel().RemoteAddr())
	// write welcome message
	ctx.Write("Hello I'm " + "go-netty")
}

func (LoggerHandler) HandleRead(ctx netty.InboundContext, message netty.Message) {
	fmt.Println("go-netty:", "->", "handle read:", message)
	// leave it to the next handler(UpperHandler)
	ctx.HandleRead(message)
}

func (LoggerHandler) HandleInactive(ctx netty.InactiveContext, ex netty.Exception) {
	fmt.Println("go-netty:", "->", "inactive:", ctx.Channel().RemoteAddr(), ex)
	// disconnected,the default processing is to close the connection
	ctx.HandleInactive(ex)
}

type UpperHandler struct {}

func (UpperHandler) HandleRead(ctx netty.InboundContext, message netty.Message) {
	// text to upper case
	text := message.(string)
	upText := strings.ToUpper(text)
	// write the result to the client
	ctx.Write(text + " -> " + upText)
}

use Netcat to send message

$ echo -n -e "Hello Go-Netty\nhttps://go-netty.com\n" | nc 127.0.0.1 9527
Hello I'm go-netty
Hello Go-Netty -> HELLO GO-NETTY
https://go-netty.com -> HTTPS://GO-NETTY.COM

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrAsyncNoSpace = errors.New("async write queue is full")

ErrAsyncNoSpace is returned when an write queue full if not writeForever flags.

View Source
var ErrServerClosed = errors.New("netty: Server closed")

ErrServerClosed is returned by the Server call Shutdown or Close.

Functions

This section is empty.

Types

type Action added in v1.1.0

type Action = func()

type ActiveContext

type ActiveContext interface {
	HandlerContext
	HandleActive()
}

ActiveContext defines an active handler

type ActiveHandler

type ActiveHandler interface {
	HandleActive(ctx ActiveContext)
}

ActiveHandler defines an active handler

type ActiveHandlerFunc

type ActiveHandlerFunc func(ctx ActiveContext)

ActiveHandlerFunc impl ActiveHandler

func (ActiveHandlerFunc) HandleActive

func (fn ActiveHandlerFunc) HandleActive(ctx ActiveContext)

HandleActive to impl ActiveHandler

type Attachment

type Attachment interface {
}

Attachment defines the object or data associated with the Channel

type Bootstrap

type Bootstrap interface {
	// Context return context
	Context() context.Context
	// Listen create a listener
	Listen(url string, option ...transport.Option) Listener
	// Connect to remote endpoint
	Connect(url string, option ...transport.Option) (Channel, error)
	// Shutdown boostrap
	Shutdown()
}

Bootstrap makes it easy to bootstrap a channel

func NewBootstrap

func NewBootstrap(option ...Option) Bootstrap

NewBootstrap create a new Bootstrap with default config.

type Channel

type Channel interface {
	// ID channel id
	ID() int64

	// Write a message through the Pipeline
	Write(Message) error

	// Trigger user event
	Trigger(event Event)

	// Close through the Pipeline
	Close(err error)

	// IsActive return true if the Channel is active and so connected
	IsActive() bool

	// Writev to write [][]byte for optimize syscall
	Writev([][]byte) (int64, error)

	// Write1 to write []byte to channel
	Write1(p []byte) (n int, err error)

	// LocalAddr local address
	LocalAddr() string

	// RemoteAddr remote address
	RemoteAddr() string

	// Transport get transport of channel
	Transport() transport.Transport

	// Pipeline get pipeline of channel
	Pipeline() Pipeline

	// Attachment get attachment
	Attachment() Attachment

	// SetAttachment set attachment
	SetAttachment(Attachment)

	// Context channel context
	Context() context.Context
	// contains filtered or unexported methods
}

Channel is defines a server-side-channel & client-side-channel

type ChannelFactory

type ChannelFactory func(id int64, ctx context.Context, pipeline Pipeline, transport transport.Transport, executor Executor) Channel

ChannelFactory to create a channel

func NewAsyncWriteChannel added in v1.3.0

func NewAsyncWriteChannel(writeQueueSize int, writeForever bool) ChannelFactory

NewAsyncWriteChannel create an async write ChannelFactory.

func NewChannel

func NewChannel() ChannelFactory

NewChannel create a ChannelFactory

type ChannelHandler

ChannelHandler defines a channel handler

type ChannelHolder added in v1.6.0

type ChannelHolder interface {
	ActiveHandler
	InactiveHandler
	// CloseAll close the all channels
	CloseAll(err error)
}

ChannelHolder to manage channels

func NewChannelHolder added in v1.6.0

func NewChannelHolder(capacity int) ChannelHolder

NewChannelHolder create a new ChannelHolder with initial capacity

type ChannelIDFactory

type ChannelIDFactory func() int64

ChannelIDFactory to create channel id

func SequenceID

func SequenceID() ChannelIDFactory

SequenceID to generate a sequence id

type ChannelInboundHandler

type ChannelInboundHandler interface {
	ActiveHandler
	InboundHandler
	InactiveHandler
}

ChannelInboundHandler defines a channel inbound handler

func ReadIdleHandler

func ReadIdleHandler(idleTime time.Duration) ChannelInboundHandler

ReadIdleHandler fire ReadIdleEvent after waiting for a reading timeout

type ChannelInitializer

type ChannelInitializer func(Channel)

ChannelInitializer to init the pipeline of channel

type ChannelOutboundHandler

type ChannelOutboundHandler interface {
	ActiveHandler
	OutboundHandler
	InactiveHandler
}

ChannelOutboundHandler defines a channel outbound handler

func WriteIdleHandler

func WriteIdleHandler(idleTime time.Duration) ChannelOutboundHandler

WriteIdleHandler fire WriteIdleEvent after waiting for a sending timeout

type CodecHandler

type CodecHandler interface {
	CodecName() string
	InboundHandler
	OutboundHandler
}

CodecHandler defines an codec handler

type Event

type Event interface {
}

Event defines user-defined event types, read-write timeout events, etc

type EventContext

type EventContext interface {
	HandlerContext
	HandleEvent(event Event)
}

EventContext defines an event handler

type EventHandler

type EventHandler interface {
	HandleEvent(ctx EventContext, event Event)
}

EventHandler defines an event handler

type EventHandlerFunc

type EventHandlerFunc func(ctx EventContext, event Event)

EventHandlerFunc impl EventHandler

func (EventHandlerFunc) HandleEvent

func (fn EventHandlerFunc) HandleEvent(ctx EventContext, event Event)

HandleEvent to impl EventHandler

type Exception

type Exception = error

Exception defines an exception

func AsException

func AsException(ex interface{}) Exception

type ExceptionContext

type ExceptionContext interface {
	HandlerContext
	HandleException(ex Exception)
}

ExceptionContext defines an exception handler

type ExceptionHandler

type ExceptionHandler interface {
	HandleException(ctx ExceptionContext, ex Exception)
}

ExceptionHandler defines an exception handler

type ExceptionHandlerFunc

type ExceptionHandlerFunc func(ctx ExceptionContext, ex Exception)

ExceptionHandlerFunc impl ExceptionHandler

func (ExceptionHandlerFunc) HandleException

func (fn ExceptionHandlerFunc) HandleException(ctx ExceptionContext, ex Exception)

HandleException to impl ExceptionHandler

type Executor added in v1.1.0

type Executor interface {
	Exec(Action)
}

func AsyncExecutor added in v1.1.0

func AsyncExecutor() Executor

type Handler

type Handler interface {
}

Handler defines an any handler At least one or more of the following types should be implemented ActiveHandler InboundHandler OutboundHandler ExceptionHandler InactiveHandler EventHandler

type HandlerContext

type HandlerContext interface {
	Channel() Channel
	Handler() Handler
	Write(message Message)
	Trigger(event Event)
	Close(err error)
	Attachment() Attachment
	SetAttachment(Attachment)
}

HandlerContext defines a base handler context

type InactiveContext

type InactiveContext interface {
	HandlerContext
	HandleInactive(ex Exception)
}

InactiveContext defines an inactive handler

type InactiveHandler

type InactiveHandler interface {
	HandleInactive(ctx InactiveContext, ex Exception)
}

InactiveHandler defines an inactive handler

type InactiveHandlerFunc

type InactiveHandlerFunc func(ctx InactiveContext, ex Exception)

InactiveHandlerFunc impl InactiveHandler

func (InactiveHandlerFunc) HandleInactive

func (fn InactiveHandlerFunc) HandleInactive(ctx InactiveContext, ex Exception)

HandleInactive to impl InactiveHandler

type InboundContext

type InboundContext interface {
	HandlerContext
	HandleRead(message Message)
}

InboundContext defines an inbound handler

type InboundHandler

type InboundHandler interface {
	HandleRead(ctx InboundContext, message Message)
}

InboundHandler defines an Inbound handler

type InboundHandlerFunc

type InboundHandlerFunc func(ctx InboundContext, message Message)

InboundHandlerFunc impl InboundHandler

func (InboundHandlerFunc) HandleRead

func (fn InboundHandlerFunc) HandleRead(ctx InboundContext, message Message)

HandleRead to impl InboundHandler

type Listener

type Listener interface {
	// Close the listener
	Close() error
	// Sync waits for this listener until it is done
	Sync() error
	// Async nonblock waits for this listener
	Async(func(error))
}

type Message

type Message interface {
}

Message defines an any message

Represent different objects in different processing steps, usually the message type handled by the codec is mainly io.Reader / []byte, in the user handler should have been converted to a protocol object.

type Option

type Option func(options *bootstrapOptions)

func WithChannel

func WithChannel(channelFactory ChannelFactory) Option

WithChannel to set ChannelFactory

func WithChannelHolder added in v1.6.0

func WithChannelHolder(holder ChannelHolder) Option

WithChannelHolder use custom ChannelHolder

func WithChannelID

func WithChannelID(channelIDFactory ChannelIDFactory) Option

WithChannelID to set ChannelIDFactory

func WithChildInitializer

func WithChildInitializer(initializer ChannelInitializer) Option

WithChildInitializer to set server side ChannelInitializer

func WithClientInitializer

func WithClientInitializer(initializer ChannelInitializer) Option

WithClientInitializer to set client side ChannelInitializer

func WithContext

func WithContext(ctx context.Context) Option

WithContext fork child context with context.WithCancel

func WithExecutor added in v1.1.0

func WithExecutor(executor Executor) Option

WithExecutor use custom Executor

func WithPipeline

func WithPipeline(pipelineFactory PipelineFactory) Option

WithPipeline to set PipelineFactory

func WithTransport

func WithTransport(transportFactory TransportFactory) Option

WithTransport to set TransportFactory

type OutboundContext

type OutboundContext interface {
	HandlerContext
	HandleWrite(message Message)
}

OutboundContext defines an outbound handler

type OutboundHandler

type OutboundHandler interface {
	HandleWrite(ctx OutboundContext, message Message)
}

OutboundHandler defines an outbound handler

type OutboundHandlerFunc

type OutboundHandlerFunc func(ctx OutboundContext, message Message)

OutboundHandlerFunc impl OutboundHandler

func (OutboundHandlerFunc) HandleWrite

func (fn OutboundHandlerFunc) HandleWrite(ctx OutboundContext, message Message)

HandleWrite to impl OutboundHandler

type Pipeline

type Pipeline interface {

	// AddFirst add a handler to the first.
	AddFirst(handlers ...Handler) Pipeline

	// AddLast add a handler to the last.
	AddLast(handlers ...Handler) Pipeline

	// AddHandler add handlers in position.
	AddHandler(position int, handlers ...Handler) Pipeline

	// IndexOf find fist index of handler.
	IndexOf(func(Handler) bool) int

	// LastIndexOf find last index of handler.
	LastIndexOf(func(Handler) bool) int

	// ContextAt get context by position.
	ContextAt(position int) HandlerContext

	// Size of handler
	Size() int

	// Channel get channel.
	Channel() Channel

	// ServeChannel serve the channel.
	ServeChannel(channel Channel)

	FireChannelActive()
	FireChannelRead(message Message)
	FireChannelWrite(message Message)
	FireChannelException(ex Exception)
	FireChannelInactive(ex Exception)
	FireChannelEvent(event Event)
}

Pipeline defines a message processing pipeline.

func NewPipeline

func NewPipeline() Pipeline

NewPipeline create a pipeline.

type PipelineFactory

type PipelineFactory func() Pipeline

PipelineFactory to create pipeline

type ReadIdleEvent

type ReadIdleEvent struct{}

ReadIdleEvent define a ReadIdleEvent

type SimpleChannelHandler

type SimpleChannelHandler = ChannelInboundHandler

SimpleChannelHandler defines ChannelInboundHandler alias

type TransportFactory

type TransportFactory transport.Factory

TransportFactory tp create transport

type WriteIdleEvent

type WriteIdleEvent struct{}

WriteIdleEvent define a WriteIdleEvent

Directories

Path Synopsis
tcp
pool/pbytes
Package pbytes contains tools for pooling byte pool.
Package pbytes contains tools for pooling byte pool.

Jump to

Keyboard shortcuts

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