websocketmanager

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2023 License: MIT Imports: 8 Imported by: 1

README

WebSocket Manager

WebSocket Manager is a Go library that simplifies managing WebSocket connections. It offers functionalities like upgrading HTTP connections to WebSocket, managing clients, broadcasting messages, and more.

This library is an abstraction on top of the gorilla/websocket library.

Installation

Install the package using go get:

go get github.com/NotCoffee418/websocketmanager

Add the package to your code:

import "github.com/NotCoffee418/websocketmanager"

Usage

Here's how to use WebSocket Manager in your Go application.

Initialize Manager

Create a new instance of the Manager type using one of the following methods:

// Create a manager with default settings
wsManager := websocketmanager.NewDefaultManager()

// Create a manager with customized settings
wsManager := websocketmanager.NewBuilder().
              WithReadBufferSize(2048).
              WithWriteBufferSize(2048).
              WithClientCleanupDisabled().
              Build()
Upgrade HTTP Connection to WebSocket

Upgrade an incoming HTTP request to a WebSocket connection:

func ginHandler(c *gin.Context) {
	wsClient <- wsManager.UpgradeClient(c.Writer, c.Request)
	//...
}

This library is agnostic to the specific Go web framework used, as long as the framework is based on Go's standard net/http package.

Assign Groups

To categorize clients into groups, use the AssignGroups method:

wsManager.AssignGroups(*client.ConnId, 1, 2)
Register Observers

To observe messages from a specific client, register an observer function:

wsManager.RegisterClientObserver(*client.ConnId, func(wsClient *websocketmanager.Client, messageType int, message []byte) {
    // Handle incoming message
})
Send Messages

To send messages, you have the following options:

  • Broadcast a message to all clients

    wsManager.BroadcastMessage(messageType, message)
    
  • Send a message to a specific group of clients

    wsManager.SendMessageToGroup(groupID, messageType, message)
    
  • Send a message to a specific client

    wsManager.SendMessageToUser(clientUUID, messageType, message)
    

Message type definitions can be found in the gorilla/websocket library.

messageType := websocket.TextMessage
Manage Clients

You can manually unregister clients or retrieve specific clients by their UUID:

  • To unregister a client:

    wsManager.Unregister(clientUUID)
    
  • To get a specific client:

    client, err := wsManager.GetWebSocketClient(clientUUID)
    
Cleanup

By default, WebSocket Manager will automatically clean up inactive clients. You can disable this during the initialization step if needed.

Contributing

Contributions are welcome. Feel free to open a pull request or issue on GitHub.

License

This project is licensed under the MIT License.

For more information, please refer to the LICENSE file in the repository.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	Conn       *websocket.Conn
	ConnId     *uuid.UUID
	Groups     []uint16
	IsAlive    bool
	CancelFunc context.CancelFunc
	// contains filtered or unexported fields
}

Client contains information about a websocket user

type ClientObservableFunc

type ClientObservableFunc func(wsClient *Client, messageType int, message []byte)

ClientObservableFunc is a function that will be called when a client sends a message

type Manager

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

Manager is a websocket manager

func NewDefaultManager

func NewDefaultManager() *Manager

NewDefaultManager Creates a new Manager with default values

func (*Manager) AssignGroups

func (wm *Manager) AssignGroups(connId uuid.UUID, groupIds ...uint16) error

AssignGroups assigns a client to one or more groups

func (*Manager) BroadcastMessage

func (wm *Manager) BroadcastMessage(messageType int, message []byte)

BroadcastMessage sends a message to all connected clients

func (*Manager) GetWebSocketClient

func (wm *Manager) GetWebSocketClient(clientUUID uuid.UUID) (*Client, error)

GetWebSocketClient returns a Client by UUID

func (*Manager) RegisterClientObserver

func (wm *Manager) RegisterClientObserver(connId uuid.UUID, messageHandler ClientObservableFunc)

func (*Manager) SendMessageToClient

func (wm *Manager) SendMessageToClient(clientId uuid.UUID, messageType int, message []byte) error

SendMessageToClient sends a message to a specific user

func (*Manager) SendMessageToGroup

func (wm *Manager) SendMessageToGroup(group uint16, messageType int, message []byte)

SendMessageToGroup sends a message to all users in a group

func (*Manager) Unregister

func (wm *Manager) Unregister(connId uuid.UUID)

Unregister unregisters a client from the manager and marks it as not alive Further messages to and from this client are discarded

func (*Manager) UpgradeClient added in v0.2.0

func (wm *Manager) UpgradeClient(w http.ResponseWriter, r *http.Request) (*Client, error)

UpgradeClient upgrades a client connection to a websocket connection It registers the client and returns a channel that will receive the Client or nil on error

type ManagerBuilder

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

ManagerBuilder is a builder for the websocket manager

func NewBuilder

func NewBuilder() *ManagerBuilder

func (*ManagerBuilder) Build

func (b *ManagerBuilder) Build() *Manager

func (*ManagerBuilder) WithClientCleanupDisabled

func (b *ManagerBuilder) WithClientCleanupDisabled() *ManagerBuilder

WithClientCleanupDisabled disables the periodic pinging of clients to check if they are still alive

func (*ManagerBuilder) WithReadBufferSize

func (b *ManagerBuilder) WithReadBufferSize(size int) *ManagerBuilder

WithReadBufferSize is a builder for the websocket manager

func (*ManagerBuilder) WithWriteBufferSize

func (b *ManagerBuilder) WithWriteBufferSize(size int) *ManagerBuilder

WithWriteBufferSize sets the write buffer size for the websocket

Jump to

Keyboard shortcuts

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