nettyws

package module
v1.0.7 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: 16 Imported by: 1

README

go-netty-ws

GoDoc license-Apache 2

An Websocket server & client written by go-netty

Install

go get github.com/go-netty/go-netty-ws@latest

API overview

type Websocket
    func NewWebsocket(options ...Option) *Websocket
    func (ws *Websocket) Close() error
    func (ws *Websocket) Listen(addr string) error
    func (ws *Websocket) Open(addr string) (Conn, error)
    func (ws *Websocket) ServeHTTP(w http.ResponseWriter, r *http.Request)
    func (ws *Websocket) UpgradeHTTP(w http.ResponseWriter, r *http.Request) (Conn, error)

type Option
    func WithAsyncWrite(writeQueueSize int, writeForever bool) Option
    func WithBinary() Option
    func WithBufferSize(readBufferSize, writeBufferSize int) Option
    func WithCompress(compressLevel int, compressThreshold int64) Option
    func WithClientHeader(header http.Header) Option
    func WithDialer(dialer Dialer) Option
    func WithMaxFrameSize(maxFrameSize int64) Option
    func WithNoDelay(noDelay bool) Option
    func WithServerHeader(header http.Header) Option
    func WithServeMux(serveMux *http.ServeMux) Option
    func WithServeTLS(tls *tls.Config) Option
    func WithValidUTF8() Option

Easy to use

Note: nettyws does not support mixed text messages and binary messages, use the WithBinary option to switch to binary message mode.

server :
// create websocket instance
var ws = nettyws.NewWebsocket()

// setup OnOpen handler
ws.OnOpen = func(conn nettyws.Conn) {
    fmt.Println("OnOpen: ", conn.RemoteAddr())
}

// setup OnData handler
ws.OnData = func(conn nettyws.Conn, data []byte) {
    fmt.Println("OnData: ", conn.RemoteAddr(), ", message: ", string(data))
    conn.Write(data)
}

// setup OnClose handler
ws.OnClose = func(conn nettyws.Conn, err error) {
    fmt.Println("OnClose: ", conn.RemoteAddr(), ", error: ", err)
}

fmt.Println("listening websocket connections ....")

// listen websocket server
if err := ws.Listen("ws://127.0.0.1:9527/ws"); nil != err {
    panic(err)
}
client :
// create websocket instance
var ws = nettyws.NewWebsocket()

// setup OnOpen handler
ws.OnOpen = func(conn nettyws.Conn) {
    fmt.Println("OnOpen: ", conn.RemoteAddr())
    conn.Write([]byte("hello world"))
}

// setup OnData handler
ws.OnData = func(conn nettyws.Conn, data []byte) {
    fmt.Println("OnData: ", conn.RemoteAddr(), ", message: ", string(data))
}

// setup OnClose handler
ws.OnClose = func(conn nettyws.Conn, err error) {
    fmt.Println("OnClose: ", conn.RemoteAddr(), ", error: ", err)
}

fmt.Println("open websocket connection ...")

// connect to websocket server
if _, err := ws.Open("ws://127.0.0.1:9527/ws"); nil != err {
    panic(err)
}
upgrade from http server:
// create websocket instance
var ws = nettyws.NewWebsocket()

// setup OnOpen handler
ws.OnOpen = func(conn nettyws.Conn) {
    fmt.Println("OnOpen: ", conn.RemoteAddr())
}

// setup OnData handler
ws.OnData = func(conn nettyws.Conn, data []byte) {
    fmt.Println("OnData: ", conn.RemoteAddr(), ", message: ", string(data))
    conn.Write(data)
}

// setup OnClose handler
ws.OnClose = func(conn nettyws.Conn, err error) {
    fmt.Println("OnClose: ", conn.RemoteAddr(), ", error: ", err)
}

fmt.Println("upgrade websocket connections ....")

// upgrade websocket connection from http server
http.Handle("/ws", ws)

// listen http server
if err := http.ListenAndServe(":9527", nil); nil != err {
    panic(err)
}

Associated

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrServerClosed = netty.ErrServerClosed

ErrServerClosed is returned by the Server call Shutdown or Close

Functions

This section is empty.

Types

type ClosedError

type ClosedError struct {
	Code   int
	Reason string
}

ClosedError returned when peer has closed the connection with appropriate code and a textual reason.

func (ClosedError) Error

func (err ClosedError) Error() string

Error implements error interface.

type Conn

type Conn interface {
	// Context returns the context of the connection.
	Context() context.Context
	// LocalAddr returns the local network address.
	LocalAddr() string
	// RemoteAddr returns the remote network address.
	RemoteAddr() string
	// Header returns the HTTP header on handshake request.
	Header() http.Header
	// SetDeadline sets the read and write deadlines associated
	// with the connection. It is equivalent to calling both
	// SetReadDeadline and SetWriteDeadline.
	SetDeadline(t time.Time) error
	// SetReadDeadline sets the deadline for future Read calls
	// and any currently-blocked Read call.
	// A zero value for t means Read will not time out.
	SetReadDeadline(t time.Time) error
	// SetWriteDeadline sets the deadline for future Write calls
	// and any currently-blocked Write call.
	// Even if write times out, it may return n > 0, indicating that
	// some of the data was successfully written.
	// A zero value for t means Write will not time out.
	SetWriteDeadline(t time.Time) error
	// Write writes a message to the connection.
	Write(message []byte) error
	// WriteClose write websocket close frame with code and close reason.
	WriteClose(code int, reason string) error
	// Close closes the connection.
	Close() error
	// Userdata returns the user-data.
	Userdata() interface{}
	// SetUserdata sets the user-data.
	SetUserdata(userdata interface{})
}

Conn is a websocket connection.

type Dialer added in v1.0.5

type Dialer interface {
	// Dial connects to the given address via the proxy.
	Dial(network, addr string) (c net.Conn, err error)
}

Dialer is a means to establish a connection.

type MessageType

type MessageType int

MessageType websocket message type

const (
	// MsgText text message
	MsgText MessageType = iota
	// MsgBinary binary message
	MsgBinary
)

type OnCloseFunc

type OnCloseFunc func(conn Conn, err error)

type OnDataFunc

type OnDataFunc func(conn Conn, data []byte)

type OnOpenFunc

type OnOpenFunc func(conn Conn)

type Option

type Option func(*options)

func WithAsyncWrite

func WithAsyncWrite(writeQueueSize int, writeForever bool) Option

WithAsyncWrite enable async write

func WithBinary

func WithBinary() Option

WithBinary switch to binary message mode

func WithBufferSize

func WithBufferSize(readBufferSize, writeBufferSize int) Option

WithBufferSize set the read/write buffer size

func WithClientHeader added in v1.0.4

func WithClientHeader(header http.Header) Option

WithClientHeader is an optional http.Header mapping that could be used to write additional headers to the handshake request.

func WithCompress

func WithCompress(compressLevel int, compressThreshold int64) Option

WithCompress enable message compression with level, messages below the threshold will not be compressed.

func WithDialer added in v1.0.5

func WithDialer(dialer Dialer) Option

WithDialer specify the client to connect to the network via a dialer.

func WithMaxFrameSize

func WithMaxFrameSize(maxFrameSize int64) Option

WithMaxFrameSize set the maximum frame size

func WithNoDelay

func WithNoDelay(noDelay bool) Option

WithNoDelay controls whether the operating system should delay packet transmission in hopes of sending fewer packets (Nagle's algorithm). The default is true (no delay), meaning that data is sent as soon as possible after a Write.

func WithServeMux

func WithServeMux(serveMux *http.ServeMux) Option

WithServeMux overwrite default http.ServeMux

func WithServeTLS

func WithServeTLS(tls *tls.Config) Option

WithServeTLS serve port with TLS

func WithServerHeader added in v1.0.4

func WithServerHeader(header http.Header) Option

WithServerHeader is an optional http.Header mapping that could be used to write additional headers to the handshake response.

func WithValidUTF8

func WithValidUTF8() Option

WithValidUTF8 enable UTF-8 checks for text frames payload

type Websocket

type Websocket struct {
	OnOpen  OnOpenFunc
	OnData  OnDataFunc
	OnClose OnCloseFunc
	// contains filtered or unexported fields
}

func NewWebsocket

func NewWebsocket(options ...Option) *Websocket

NewWebsocket create websocket instance with options

func (*Websocket) Close

func (ws *Websocket) Close() error

Close the listeners and connections

func (*Websocket) Listen

func (ws *Websocket) Listen(addr string) error

Listen websocket connections on address

func (*Websocket) Open

func (ws *Websocket) Open(addr string) (conn Conn, err error)

Open websocket connection from address

func (*Websocket) ServeHTTP added in v1.0.5

func (ws *Websocket) ServeHTTP(writer http.ResponseWriter, request *http.Request)

func (*Websocket) UpgradeHTTP

func (ws *Websocket) UpgradeHTTP(writer http.ResponseWriter, request *http.Request) (conn Conn, err error)

UpgradeHTTP upgrades http connection to the websocket connection

Directories

Path Synopsis
autobahn

Jump to

Keyboard shortcuts

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