websocket

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2025 License: MIT Imports: 15 Imported by: 1

README

websocket

GoDoc Go Report Card Tests codecov

Simple websocket library for golang

Installation

go get github.com/pkgz/websocket

Example

Echo
package main

import (
	"context"
	"github.com/pkgz/websocket"
	"net/http"
)

func main() {
	wsServer := websocket.Start(context.Background())

	r := http.NewServeMux()
	r.HandleFunc("/ws", wsServer.Handler)

	wsServer.On("echo", func(c *websocket.Conn, msg *websocket.Message) {
		_ = c.Emit("echo", msg.Data)
	})

	_ = http.ListenAndServe(":8080", r)
}
Channel
package main

import (
	"context"
	"github.com/pkgz/websocket"
	"net/http"
)

func main() {
	wsServer := websocket.Start(context.Background())

	r := http.NewServeMux()
	r.HandleFunc("/ws", wsServer.Handler)

	ch := wsServer.NewChannel("test")
	wsServer.OnConnect(func(c *websocket.Conn) {
		ch.Add(c)
		ch.Emit("connection", "new connection come")
	})

	_ = http.ListenAndServe(":8080", r)
}
Hello World
package main

import (
	"context"
	"github.com/pkgz/websocket"
	"github.com/gobwas/ws"
	"net/http"
)

func main () {
	r := http.NewServeMux()
	wsServer := websocket.Start(context.Background())

	r.HandleFunc("/ws", wsServer.Handler)
	wsServer.OnMessage(func(c *websocket.Conn, h ws.Header, b []byte) {
		c.Send("Hello World")
	})

	http.ListenAndServe(":8080", r)
}

Benchmark

Autobahn

All tests was runned by Autobahn WebSocket Testsuite v0.8.0/v0.10.9. Results:

Code Name Status
1 Framing Pass
2 Pings/Pongs Pass
3 Reserved Bits Pass
4 Opcodes Pass
5 Fragmentation Pass
6 UTF-8 Handling Pass
7 Close Handling Pass
9 Limits/Performance Pass
10 Misc Pass
12 WebSocket Compression (different payloads) Unimplemented
13 WebSocket Compression (different parameters) Unimplemented

Licence

MIT License

Documentation

Overview

Package websocket implements the WebSocket protocol with additional functions.

Examples

Echo server:

package main

import (
	"github.com/pkgz/websocket"
	"net/http"
)

func main () {
	r := http.NewServeMux()
	wsServer := websocket.Start(context.Background())

	r.HandleFunc("/ws", wsServer.Handler)

	wsServer.On("echo", func(ctx context.Context, c *websocket.Conn, msg *websocket.Message) {
		c.Emit("echo", msg.Data)
	})

	http.ListenAndServe(":8080", r)
}

Websocket with group:

package main

import (
	"github.com/pkgz/websocket"
	"net/http"
)

func main () {
	r := http.NewServeMux()

	wsServer := websocket.Start(context.Background())

	ch := wsServer.NewChannel("test")

	wsServer.OnConnect(func(ctx context.Context, c *websocket.Conn) {
		ch.Add(c)
		ch.Emit("connection", []byte("new connection come"))
	})

	r.HandleFunc("/ws", wsServer.Handler)
	http.ListenAndServe(":8080", r)
}

Index

Constants

View Source
const TextMessage = false

Variables

View Source
var PingInterval = time.Second * 5

Functions

This section is empty.

Types

type Channel

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

Channel represent group of connections (similar to group in socket.io).

func (*Channel) Add

func (c *Channel) Add(conn *Conn)

Add connection to channel.

func (*Channel) Count

func (c *Channel) Count() int

Count return number of live connections in channel.

func (*Channel) Emit

func (c *Channel) Emit(name string, data interface{})

Emit message to all connections in channel.

func (*Channel) ID

func (c *Channel) ID() string

ID return channel id.

func (*Channel) Purge added in v1.2.1

func (c *Channel) Purge()

Purge remove all connections from channel.

func (*Channel) Remove

func (c *Channel) Remove(conn *Conn)

Remove connection from channel.

type Conn

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

Conn websocket connection

func (*Conn) Close

func (c *Conn) Close() error

Close closing websocket connection.

func (*Conn) Emit

func (c *Conn) Emit(name string, data interface{}) error

Emit message to connection.

func (*Conn) ID added in v1.2.1

func (c *Conn) ID() string

ID return an connection identifier (could be not unique)

func (*Conn) Param added in v1.2.1

func (c *Conn) Param(key string) string

Param gets the value from url params. If there are no values associated with the key, Get returns the empty string. To access multiple values, use the map directly.

func (*Conn) Send

func (c *Conn) Send(data any) error

Send data to connection.

func (*Conn) Write

func (c *Conn) Write(h ws.Header, b []byte) error

Write byte array to connection.

type HandlerFunc

type HandlerFunc func(ctx context.Context, c *Conn, msg *Message)

HandlerFunc is a type for handle function all function which has callback have this struct as first element returns pointer to connection its give opportunity to close connection or emit message to exactly this connection.

type Message

type Message struct {
	Name string `json:"name"`
	Data []byte `json:"data"`
}

Message is a struct for data which sending between application and clients. Name using for matching callback function in On function. Body will be transformed to byte array and returned to callback.

type Server

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

Server allows keeping connection list, broadcast channel and callbacks list.

func New added in v1.2.0

func New() *Server

New websocket server handler with the provided options.

func Start added in v1.2.0

func Start(ctx context.Context) *Server

Start instantly create and run websocket server.

func (*Server) Channel added in v1.2.1

func (s *Server) Channel(id string) *Channel

Channel find and return the channel.

func (*Server) Channels added in v1.2.2

func (s *Server) Channels() []string

Channels returns channels id with live connections.

func (*Server) Count

func (s *Server) Count() int

Count return number of active connections.

func (*Server) Emit

func (s *Server) Emit(name string, data []byte)

Emit message to all connections.

func (*Server) Handler

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

Handler get upgrade connection to RFC 6455 and starting listener for it.

func (*Server) IsClosed added in v1.2.0

func (s *Server) IsClosed() bool

IsClosed return the state of websocket server.

func (*Server) NewChannel

func (s *Server) NewChannel(id string) *Channel

NewChannel create new channel and proxy channel delConn for handling connection closing.

func (*Server) On

func (s *Server) On(name string, f HandlerFunc)

On adding callback for message.

func (*Server) OnConnect

func (s *Server) OnConnect(f func(ctx context.Context, c *Conn))

OnConnect function which will be called when new connections come.

func (*Server) OnDisconnect

func (s *Server) OnDisconnect(f func(ctx context.Context, c *Conn))

OnDisconnect function which will be called when new connections come.

func (*Server) OnMessage

func (s *Server) OnMessage(f func(ctx context.Context, c *Conn, h ws.Header, b []byte))

OnMessage handling byte message. This function works as echo by default

func (*Server) Run

func (s *Server) Run(ctx context.Context)

Run start go routine which listening for channels.

func (*Server) SendTo added in v1.2.1

func (s *Server) SendTo(id string, name string, message *Message) error

SendTo send message to channel with id.

func (*Server) Shutdown

func (s *Server) Shutdown() error

Shutdown must be called before application died its goes throw all connection and closing it and stopping all goroutines.

Jump to

Keyboard shortcuts

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