websocket

package module
v0.0.0-...-644f707 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2017 License: MIT Imports: 18 Imported by: 0

README

license Documentation Status Build Status Coverage Status Go Report Card

This library is under development

Websocket

A WebSocket implementation on top of the fasthttp.

Implementation

The RFC 6455 describes the WebSocket Protocol. This is the main source of information used for this implementation.

Motivation

Yay! The Gorilla WebSocket works great, and some code of this library are actually based on their implementation, but it does not support the Valyala Fasthttp library.

At first, I tried to use a the Leavengood (https://github.com/leavengood/websocket) fork of the Gorilla Websocket. However, I could not find it useful. Actually I could not find even a reference for the fasthttp at the master branch. How strange is that!?

Hence, I decided to come up with a websocket protocol implementation aiming specially the fasthttp.

Testing

In order to make sure everything is working properly, after each minor release an Autobahn Test Suite report will be released to keep track of the supported features.

More info at https://github.com/crossbario/autobahn-testsuite.

Documentation

Index

Constants

View Source
const (
	// ConnectionStateConnecting represents the initial state of a connection
	ConnectionStateConnecting = iota
	// ConnectionStateOpen represents a opened health connection
	ConnectionStateOpen
	// ConnectionStateClosing represents a connection that is closing
	ConnectionStateClosing
	// ConnectionStateClosed represents a closed connection
	ConnectionStateClosed
)
View Source
const (
	// OPCodeContinuationFrame is the continuation operation code of the dataframe
	OPCodeContinuationFrame byte = 0
	// OPCodeTextFrame is the text message operation code of the dataframe
	OPCodeTextFrame byte = 1
	// OPCodeBinaryFrame is the binary message operation code of the dataframe
	OPCodeBinaryFrame byte = 2
	// OPCodeConnectionCloseFrame is the connection close operation code of the dataframe
	OPCodeConnectionCloseFrame byte = 8
	// OPCodePingFrame is the ping operation code of the dataframe
	OPCodePingFrame byte = 9
	// OPCodePongFrame is the pong operation code of the dataframe
	OPCodePongFrame byte = 10
)

Variables

View Source
var (
	ErrUnexpectedEndOfPacket = errors.New("Unexpected end of packet")
	ErrConnectionClosing     = errors.New("Connection closing")
	ErrConnectionClosed      = errors.New("Connection closed")
	ErrProtocolError         = errors.New("Protocol error")
	ErrControlFragmented     = errors.New("Control packet fragmented")
	ErrTimeout               = errors.New("Timeout")
	ErrMissingMaskKey        = errors.New("Missing mask key")
	ErrWrongMaskKey          = errors.New("Wrong mask key")
	ErrWrongClosingCode      = errors.New("Wrong closing code")
)

Functions

func DecodePacket

func DecodePacket(buff []byte) (fin bool, rsv1 bool, rsv2 bool, rsv3 bool, opcode byte, payloadLen uint64, maskingKey []byte, payload []byte, err error)

DecodePacket splits all the information from the raw packet and return it.

func DecodePacketFromReader

func DecodePacketFromReader(reader io.Reader, buff []byte, deadline time.Time) (fin bool, rsv1 bool, rsv2 bool, rsv3 bool, opcode byte, payloadLen uint64, maskingKey []byte, payload []byte, err error)

func Deflate

func Deflate(dst, src []byte) ([]byte, error)

Deflate deflates a flated package

func EncodePacket

func EncodePacket(fin bool, rsv1 bool, rsv2 bool, rsv3 bool, opcode byte, payloadLen uint64, maskingKey []byte, payload []byte) ([]byte, error)

EncodePacket generates a byte array with the packet encoded according with the RFC 6455

func Flate

func Flate(dst, src []byte) ([]byte, int, error)

Flate compress the given src into the dst buffer It returns the amount of bytes written or an error.

func IsUnexpectedEndOfPacket

func IsUnexpectedEndOfPacket(err error) bool

IsUnexpectedEndOfPacket checks if the given error is of type unexpected end of packet

func Unmask

func Unmask(buff, mask []byte)

Unmask unmasks a masked payload.

There is no Mask method. Since the masking procedure is a bitwise not, applying Unmask will toggle the un/masking.

Types

type BaseConnection

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

BaseConnection represents a connection with a client

func NewConn

func NewConn(conn net.Conn) *BaseConnection

NewConn initialized and return a new websocket.BaseConnection instance

func (*BaseConnection) Close

func (c *BaseConnection) Close() error

Close implements the websocket.Connection.Close

func (*BaseConnection) CloseWithReason

func (c *BaseConnection) CloseWithReason(reason ConnectionCloseReason) error

CloseWithReason implements the websocket.Connection.CloseWithReason

func (*BaseConnection) Conn

func (c *BaseConnection) Conn() net.Conn

Conn implements the websocket.Connection.Conn

func (*BaseConnection) Context

func (c *BaseConnection) Context() interface{}

func (*BaseConnection) Init

func (c *BaseConnection) Init(ctx *ConnectionContext)

Init implements the websocket.Connection.Init

func (*BaseConnection) IsClosed

func (c *BaseConnection) IsClosed() bool

IsClosed implements the websocket.Connection.IsClosed

func (*BaseConnection) Read

func (c *BaseConnection) Read(b []byte) (int, error)

Read implements the websocket.Connection.Read

func (*BaseConnection) ReadPacket

func (c *BaseConnection) ReadPacket() (fin bool, opcode byte, payload []byte, err error)

ReadPacket implements the websocket.Connection.ReadPacket

func (*BaseConnection) ReadPacketTimeout

func (c *BaseConnection) ReadPacketTimeout(timeout time.Duration) (bool, byte, []byte, error)

ReadPacketTimeout implements the websocket.Connection.ReadPacketTimeout

func (*BaseConnection) Reset

func (c *BaseConnection) Reset()

Reset cleans up all the data and prepare the instance for being placed back on the pool, for avoiding allocation.

func (*BaseConnection) SetContext

func (c *BaseConnection) SetContext(value interface{})

func (*BaseConnection) State

func (c *BaseConnection) State() ConnectionState

State implements the websocket.Connection.State

func (*BaseConnection) Terminate

func (c *BaseConnection) Terminate() error

Terminate implements the websocket.Connection.Terminate

func (*BaseConnection) Write

func (c *BaseConnection) Write(b []byte) (int, error)

Write implements the websocket.Connection.Write

func (*BaseConnection) WritePacket

func (c *BaseConnection) WritePacket(opcode byte, data []byte) error

WritePacket implements the websocket.Connection.WritePacket

func (*BaseConnection) WritePacketTimeout

func (c *BaseConnection) WritePacketTimeout(timeout time.Duration, opcode byte, data []byte) error

WritePacketTimeout implements the websocket.Connection.WritePacketTimeout

type Connection

type Connection interface {
	Init(context *ConnectionContext)
	Reset()

	Conn() net.Conn

	State() ConnectionState

	Context() interface{}
	SetContext(value interface{})

	Read(buffer []byte) (int, error)
	Write(data []byte) (int, error)

	ReadPacket() (bool, byte, []byte, error)
	ReadPacketTimeout(timeout time.Duration) (bool, byte, []byte, error)

	WritePacket(opcode byte, payload []byte) error
	WritePacketTimeout(timeout time.Duration, opcode byte, payload []byte) error

	ReadMessage() (MessageType, []byte, error)
	ReadMessageTimeout(timeout time.Duration) (MessageType, []byte, error)
	WriteMessage(opcode MessageType, payload []byte) error
	WriteMessageTimeout(timeout time.Duration, opcode MessageType, payload []byte) error

	IsClosed() bool
	Close() error
	CloseWithReason(reason ConnectionCloseReason) error
	Terminate() error
}

Connection is the minimum representation of a websocket connection

type ConnectionCloseReason

type ConnectionCloseReason uint16

ConnectionCloseReason represents the reason informed by the endpoint for closing the connection.

const (
	// ConnectionCloseReasonNormal happens when the endpoint simply want to end
	// the connection
	ConnectionCloseReasonNormal ConnectionCloseReason = 1000
	// ConnectionCloseReasonGoingDown happens when the server is going down, or
	// the client is navigating away to another page.
	ConnectionCloseReasonGoingDown ConnectionCloseReason = 1001
	// ConnectionCloseReasonProtocolError happens when there is any error on the
	// protocol
	ConnectionCloseReasonProtocolError ConnectionCloseReason = 1002
	// ConnectionCloseReasonDataTypeUnsupported happens when the endpoint
	// receives a datatype it cannot accept.
	ConnectionCloseReasonDataTypeUnsupported ConnectionCloseReason = 1003
	// ConnectionCloseReasonInconsistentType happens when the endpoint receives
	// a message inconsistent with the type of the message
	ConnectionCloseReasonInconsistentType ConnectionCloseReason = 1007
	// ConnectionCloseReasonPolicyViolation happens when the endpoint receives a
	// message that violates its policy
	ConnectionCloseReasonPolicyViolation ConnectionCloseReason = 1008
	// ConnectionCloseReasonMessageTooBig happens when the endpoint receives a
	// message bigger than it can process.
	ConnectionCloseReasonMessageTooBig ConnectionCloseReason = 1009
	// ConnectionCloseReasonCouldNotNegotiateExtensions happens when the client
	// and the server fail to negotiate the extensions.
	ConnectionCloseReasonCouldNotNegotiateExtensions ConnectionCloseReason = 1010
	// ConnectionCloseReasonUnexpected happens when the server is terminating
	// the connection because it encoutered an unexpected condition
	ConnectionCloseReasonUnexpected ConnectionCloseReason = 1011
)

type ConnectionContext

type ConnectionContext struct {
	Conn       net.Conn
	Compressed bool
}

ConnectionContext saves all the data that will be forwarded to the manager from the hijacked connection.

type ConnectionErrorHandler

type ConnectionErrorHandler func(conn Connection, err error)

ConnectionErrorHandler represents the handler that will receive the connection reference and an error that occurred.

type ConnectionHandler

type ConnectionHandler func(conn Connection) error

ConnectionHandler represents the handler that the Upgrader will trigger after successfully upgrading the connection.

type ConnectionState

type ConnectionState byte

ConnectionState represents the state of the websocket connection.

type HandshakeError

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

HandshakeError represents an handshake error while upgrading a connection.

func (HandshakeError) Error

func (e HandshakeError) Error() string

type ListenableManager

type ListenableManager struct {
	ReadTimeout time.Duration

	OnConnect      ConnectionHandler
	OnMessage      MessageHandler
	OnMessageError ConnectionErrorHandler
	OnClose        ConnectionHandler
	// contains filtered or unexported fields
}

ListenableManager is a websocket.Manager that implements a set of handlers that will be called when any events occurs

func NewListeableManager

func NewListeableManager() *ListenableManager

NewListeableManager returns a new instance of the websocket.ListenableManager

func (*ListenableManager) Accept

func (cm *ListenableManager) Accept(ctx *ConnectionContext) (err error)

Accept implements the websocket.Manager.Accept method

type Manager

type Manager interface {
	// Accept handles the incoming connection.
	Accept(conn *ConnectionContext) error
}

Manager handles all the tasks .

type MessageHandler

type MessageHandler func(conn Connection, opcode MessageType, payload []byte) error

MessageHandler represents the handler for a message.

type MessageType

type MessageType byte

MessageType represents the type of message defined by the RFC 6455

const (
	// MessageTypeContinuation represents a continuation
	MessageTypeContinuation MessageType = 0
	// MessageTypeText represents a text frame
	MessageTypeText MessageType = 1
	// MessageTypeBinary represents a binary frame
	MessageTypeBinary MessageType = 2
	// MessageTypeConnectionClose represents a closing message and the
	// connection will be closed right away
	MessageTypeConnectionClose MessageType = 8
	// MessageTypePing represents a ping frame
	MessageTypePing MessageType = 9
	// MessageTypePong represents a pong frame
	MessageTypePong MessageType = 10
)

type SimpleConnection

type SimpleConnection struct {
	BaseConnection
	// contains filtered or unexported fields
}

SimpleConnection represents a connection with a client

func NewSimpleConn

func NewSimpleConn(conn net.Conn) *SimpleConnection

NewSimpleConn initialized and return a new websocket.BaseConnection instance

func (*SimpleConnection) ReadMessage

func (c *SimpleConnection) ReadMessage() (MessageType, []byte, error)

ReadMessage implements the websocket.Connection.ReadMessage method

func (*SimpleConnection) ReadMessageTimeout

func (c *SimpleConnection) ReadMessageTimeout(timeout time.Duration) (MessageType, []byte, error)

ReadMessageTimeout implements the websocket.Connection.ReadMessageTimeout method

func (*SimpleConnection) WriteMessage

func (c *SimpleConnection) WriteMessage(opcode MessageType, payload []byte) error

WriteMessage implements the websocket.Connection.WriteMessage method

func (*SimpleConnection) WriteMessageTimeout

func (c *SimpleConnection) WriteMessageTimeout(timeout time.Duration, opcode MessageType, payload []byte) error

WriteMessageTimeout implements the websocket.Connection.WriteMessageTimeout method

type SimpleManager

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

SimpleManager is a manager that will let the handler property manage all reading and writing of the connection.

func NewSimpleManager

func NewSimpleManager(handler ConnectionHandler) *SimpleManager

NewSimpleManager creates a new instance of the SimpleManager

func (*SimpleManager) Accept

func (cm *SimpleManager) Accept(ctx *ConnectionContext) error

Accept implements the websocket.Manager.Accept method

type Upgrader

type Upgrader struct {
	Error func(ctx *fasthttp.RequestCtx, reason error)
	// contains filtered or unexported fields
}

Upgrader implements build the HTTP Package for upgrading the connection from regular HTTP Request to a Websocket request.

func NewUpgrader

func NewUpgrader(manager Manager) *Upgrader

NewUpgrader returns a new instance of an websocket.Upgrader

func (*Upgrader) Upgrade

func (u *Upgrader) Upgrade(ctx *fasthttp.RequestCtx) error

Upgrade upgrades the request to the websocket protocol

TODO To document

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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