engine

package
v0.0.0-...-eb1420b Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2020 License: BSD-3-Clause Imports: 21 Imported by: 0

README

engine

GoDoc license

engine.io in #Go

Install

vgo get -v github.com/Mindgamesnl/socketio/engine

Example

Server:

package main

import (
	"fmt"
	"net/http"
	"os"
	"time"

	"github.com/Mindgamesnl/socketio/engine"
)

func main() {
	server, _ := engine.NewServer(time.Second*25, time.Second*5, func(so *engine.Socket) {
		so.On(engine.EventMessage, engine.Callback(func(typ engine.MessageType, data []byte) {
			switch typ {
			case engine.MessageTypeString:
				fmt.Fprintf(os.Stderr, "txt: %s\n", data)
			case engine.MessageTypeBinary:
				fmt.Fprintf(os.Stderr, "bin: %x\n", data)
			default:
				fmt.Fprintf(os.Stderr, "???: %x\n", data)
			}
		}))
		so.On(engine.EventPing, engine.Callback(func(_ engine.MessageType, _ []byte) {
			fmt.Fprintf(os.Stderr, "socket ping\n")
		}))
		so.On(engine.EventClose, engine.Callback(func(_ engine.MessageType, _ []byte) {
			fmt.Fprintf(os.Stderr, "socket close\n")
		}))
		so.On(engine.EventUpgrade, engine.Callback(func(_ engine.MessageType, _ []byte) {
			fmt.Fprintf(os.Stderr, "socket upgrade\n")
		}))
	})
	http.ListenAndServe(":8081", server)
}

Client:

const url = 'ws://localhost:8081';
const eio = require('engine.io-client')(url, {});

eio.on('open', function() {
    console.log('open');
    eio.on('message', function(data) {
        if (data instanceof ArrayBuffer || data instanceof Buffer) {
            var a = new Uint8Array(data);
            console.log('receive: binary '+a.toString());
        } else {
            console.log('receive: text '+data);
        }
    });
    eio.on('upgrade', function() {
        console.log('upgrade');
    });
    eio.on('ping', function() {
        console.log('ping');
    });
    eio.on('pong', function() {
        console.log('pong');
    })
    eio.on('close', function() {
        console.log('close');
        process.exit(0);
    });
    eio.on('error', function(err) {
        console.log('error: '+err);
        process.exit(-1);
    });

    var text = 'hello';
    var ab = new ArrayBuffer(4);
    var a = new Uint8Array(ab);
    a.set([1,2,3,4]);

    console.log("sending: text "+text);
    eio.send(text);

    console.log("sending: binary 1,2,3,4");
    eio.send(ab);

    setInterval(function() {
        console.log("sending: text "+text);
        eio.send(text);

        console.log("sending: binary 1,2,3,4");
        eio.send(ab);
    }, 5*1000);
});

Documentation

Index

Examples

Constants

View Source
const (
	// EventOpen is fired upon successful connection.
	EventOpen event = "open"
	// EventMessage is fired when data is received from the server.
	EventMessage event = "message"
	// EventClose is fired upon disconnection. In compliance with the WebSocket API spec, this event may be fired even if the open event does not occur (i.e. due to connection error or close()).
	EventClose event = "close"
	// EventError is fired when an error occurs.
	EventError event = "error"
	// EventUpgrade is fired upon upgrade success, after the new transport is set
	EventUpgrade event = "upgrade"
	// EventPing is fired upon flushing a ping packet (ie: actual packet write out)
	EventPing event = "ping"
	// EventPong is fired upon receiving a pong packet.
	EventPong event = "pong"
)
View Source
const (

	// Version is engine.io-protocol version
	Version = "3"
)

Variables

View Source
var (
	// ErrPollingConnClosed implies connection closed; fatal.
	ErrPollingConnClosed = errors.New("polling connection closed")
	// ErrPollingConnReadTimeout implies connection read timeout; fatal.
	ErrPollingConnReadTimeout = errors.New("polling connection read timeout")
	// ErrPollingConnWriteTimeout implies connection write timeout; fatal.
	ErrPollingConnWriteTimeout = errors.New("polling connection write timeout")
	// ErrPollingConnPaused implies connection paused; temperary.
	ErrPollingConnPaused = errors.New("polling connection paused")
	// ErrPollingRequestCanceled implies request canceled; temperary.
	ErrPollingRequestCanceled = errors.New("polling request canceled")
)
View Source
var (
	// ErrPauseNotSupported indicates that a connection does not support PAUSE (e.g. websocket)
	ErrPauseNotSupported = errors.New("transport pause unsupported")
	// ErrPollingOriginNotAllowed indicates that the connection is refused due to CheckOrigin failure
	ErrPollingOriginNotAllowed = errors.New("polling: request origin not allowed")
)
View Source
var (
	// ErrInvalidPayload indicates received data is invalid or unrecognized when decoding payload
	ErrInvalidPayload = errors.New("invalid payload")
)

Functions

This section is empty.

Types

type Acceptor

type Acceptor interface {
	Accept(w http.ResponseWriter, r *http.Request) (conn Conn, err error)
}

Acceptor accepts a connecting requests and creates a connection instance (server side)

var PollingAcceptor Acceptor = &pollingAcceptor{}

PollingAcceptor is an Acceptor instance for polling

type Barrier

type Barrier interface {
	Wait() // Wait is blocking if `Pause` called and non-blocking after `Resume` called
	Pause()
	Resume()
}

type Callable

type Callable interface {
	Call(so *Socket, typ MessageType, data []byte)
}

Callable is event handle to be called when event occurs

type Callback

type Callback func(so *Socket, typ MessageType, data []byte)

Callback is a Callable func, default event handler

func (Callback) Call

func (h Callback) Call(so *Socket, typ MessageType, data []byte)

Call implements Callable interface

type Client

type Client struct {
	*Socket
	// contains filtered or unexported fields
}

Client is engine.io client

func Dial

func Dial(rawurl string, requestHeader http.Header, dialer Dialer) (c *Client, err error)

Dial connects to a engine.io server represented by `rawurl` and create Client instance on success.

Example
c, err := Dial("ws://localhost:8080/engine.io/", nil, WebsocketTransport)
if err != nil {
	log.Printf("dial err=%s", err)
	return
}
defer c.Close()
log.Printf("id=%s\n", c.Sid())
Output:

func (*Client) Close

func (c *Client) Close() (err error)

Close closes underlying connection and signals stop for background workers

func (Client) On

func (e Client) On(event event, callable Callable)

type Conn

type Conn interface {
	PacketReader
	PacketWriter
	io.Closer
	FlushOut() []*Packet
	FlushIn() []*Packet
	SetReadDeadline(t time.Time) error
	SetWriteDeadline(t time.Time) error
	Pause() error
	Resume() error
	LocalAddr() net.Addr
	RemoteAddr() net.Addr
	// contains filtered or unexported methods
}

Conn is abstraction of bidirectional engine.io connection

type Dialer

type Dialer interface {
	Dial(rawurl string, requestHeader http.Header) (conn Conn, err error)
}

Dialer dials to remote server and returns a connection instance (client side)

type MessageType

type MessageType byte

MessageType indicates type of an engine.io Message

const (
	// MessageTypeString indicates Message encoded as string
	MessageTypeString MessageType = iota
	// MessageTypeBinary indicates Message encoded as binary
	MessageTypeBinary
)

func (MessageType) String

func (m MessageType) String() string

String returns string representation of a MessageType

type OriginChecker

type OriginChecker interface {
	CheckOrigin(*http.Request) bool
}

type Packet

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

Packet is abstraction of message, exchaged between engine.io server and client

func (*Packet) WriteTo

func (p *Packet) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements io.WriterTo interface, which encodes p and writes to w.

type PacketReader

type PacketReader interface {
	ReadPacket() (p *Packet, err error)
}

PacketReader reads data from remote and outputs a Packet when appropriate

type PacketType

type PacketType byte

PacketType indicates type of an engine.io Packet

const (
	// PacketTypeOpen is sent from the server when a new transport is opened (recheck)
	PacketTypeOpen PacketType = iota
	// PacketTypeClose requests the close of this transport but does not shutdown the connection itself.
	PacketTypeClose
	// PacketTypePing is sent by the client. Server should answer with a pong packet containing the same data
	PacketTypePing
	// PacketTypePong is sent by the server to respond to ping packets.
	PacketTypePong
	// PacketTypeMessage denotes actual message, client and server should call their callbacks with the data.
	PacketTypeMessage
	// PacketTypeUpgrade is sent by the client requesting the server to flush its cache on the old transport and switch to the new transport.
	PacketTypeUpgrade
	// PacketTypeNoop denotes a noop packet. Used primarily to force a poll cycle when an incoming websocket connection is received.
	PacketTypeNoop
)

func (PacketType) String

func (p PacketType) String() string

String returns string representation of a PacketType

type PacketWriter

type PacketWriter interface {
	WritePacket(p *Packet) error
}

PacketWriter accepts a Packet and sends to remote

type Parameters

type Parameters struct {
	SID          string   `json:"sid"`
	Upgrades     []string `json:"upgrades"`
	PingInterval int      `json:"pingInterval"`
	PingTimeout  int      `json:"pingTimeout"`
}

Parameters describes engine.io connection attributes, sending from server to client upon handshaking.

type Payload

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

Payload is a series of Packets

func (*Payload) ReadFrom

func (p *Payload) ReadFrom(r io.Reader) (n int64, err error)

ReadFrom implements io.ReaderFrom interface, which decodes data from r and unmarshals to p.

func (Payload) WriteTo

func (p Payload) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements io.WriterTo interface, which encodes packets in p and writes to w.

type Server

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

Server is engine.io server implementation

Example
server, _ := NewServer(time.Second*5, time.Second*5, func(so *Socket) {
	log.Println("connect", so.RemoteAddr())
})
server.On(EventMessage, Callback(func(so *Socket, typ MessageType, data []byte) {
	switch typ {
	case MessageTypeString:
		log.Printf("txt: %s\n", data)
	case MessageTypeBinary:
		log.Printf("bin: %x\n", data)
	default:
		log.Printf("???: %x\n", data)
	}
}))
server.On(EventPing, Callback(func(so *Socket, _ MessageType, _ []byte) {
	log.Printf("socket ping\n")
}))
server.On(EventClose, Callback(func(so *Socket, _ MessageType, _ []byte) {
	log.Printf("socket close\n")
}))
server.On(EventUpgrade, Callback(func(so *Socket, _ MessageType, _ []byte) {
	log.Printf("socket upgrade\n")
}))
defer server.Close()
log.Fatalln(http.ListenAndServe("localhost:8081", server))
Output:

func NewServer

func NewServer(interval, timeout time.Duration, onOpen func(*Socket), oc ...OriginChecker) (*Server, error)

NewServer creates a enine.io server instance

func (*Server) Close

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

Close signals stop to background workers and closes server

func (Server) Get

func (s Server) Get(id string) (ß *Socket, b bool)

func (Server) NewSession

func (s Server) NewSession(conn Conn, readTimeout, writeTimeout time.Duration, query url.Values) *Socket

func (Server) On

func (e Server) On(event event, callable Callable)

func (Server) Remove

func (s Server) Remove(id string)

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP impements http.Handler interface

type Socket

type Socket struct {
	Conn
	Query url.Values

	sync.RWMutex
	// contains filtered or unexported fields
}

Socket is engine.io connection encapsulation

func (*Socket) Close

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

Close closes underlying connection and background emitter

func (*Socket) Emit

func (s *Socket) Emit(event event, msgType MessageType, args interface{}) (err error)

Emit sends event data to remote peer

func (*Socket) GetHeader

func (s *Socket) GetHeader(key string) (val string)

GetHeader returns the value in http header from client request specified by `key`

func (*Socket) HasBeenClosed

func (s *Socket) HasBeenClosed() bool

Wether it has been closed

func (*Socket) Read

func (s *Socket) Read() (p *Packet, err error)

Read returns a Packet upon success or error on failure

func (*Socket) Send

func (s *Socket) Send(args interface{}) (err error)

Send is short for Emitting message event

func (*Socket) ServeHTTP

func (s *Socket) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler

func (*Socket) SetHasBeenClosed

func (s *Socket) SetHasBeenClosed(state bool)

Wether it has been closed

func (*Socket) SetHeader

func (s *Socket) SetHeader(key, value string)

SetHeader sets (key,value) in http header

func (*Socket) Sid

func (s *Socket) Sid() string

Sid returns socket session id, assigned by server.

type Transport

type Transport interface {
	Dialer
	Acceptor
	Name() string
}

Transport is compositionof Dailer and Acceptor

var PollingTransport Transport = &pollingTransport{}

PollingTransport is a Transport instance for polling

var WebsocketTransport Transport = &websocketTransport{}

WebsocketTransport is a Transport instance for websocket

Jump to

Keyboard shortcuts

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