ws

package module
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2022 License: MIT Imports: 11 Imported by: 0

README

WebSocket-Go

WebSocket-Go is an implementation for Golang, which is a realtime, fast and scalable websocket(Socket.IO-like) library based on Gorilla WebSocket, go-redis and uuid.

Compatible with Socket.IO JS client version 2.x & 3.x

Installation

Install:

go get github.com/mileskies/websocket-go

Import:

import "github.com/mileskies/websocket-go"

Example

Requires a running Redis service for handling message exchange from replicas of your application runs on different machines or container.

package main

import (
    "log"
    "net/http"

    "github.com/go-redis/redis/v7"
    "github.com/gorilla/websocket"
    ws "github.com/mileskies/websocket-go"
)

func main() {
    redisClient := redis.NewClient(&redis.Options{
        Addr:     "127.0.0.1:6379",
        Password: "",
        DB:       0,
    })
    if _, err := redisClient.Ping().Result(); err != nil {
        panic(err)
    }

    wsServer = ws.NewServer(redisClient)

    wsServer.On("onConnect", func(c ws.Client) error {
		fmt.Println("connected")

        c.On("msg", func(msg string) {
            fmt.Println("msg:", msg)
            c.Emit("msg", msg)
        })
        c.On("onError", func(e error) {
            fmt.Println("error:", e)
        })
        c.On("onDisconnect", func(msg string) {
            fmt.Println("disconnect:", msg)
        })
		return nil
	})

    http.HandleFunc("/socket.io/*any", func(w http.ResponseWriter, r *http.Request) {
        wsServer.ServeHTTP(w, r)
    })
    log.Fatal(http.ListenAndServe(":80", nil))
}

Also redis sentinel

    redisClient := redis.NewFailoverClient(&redis.FailoverOptions{
        MasterName:    "master",
        SentinelAddrs: []string{":26379"},
    })
    if _, err := redisClient.Ping().Result(); err != nil {
        panic(err)
    }

How to use

Server
  • Broadcast message to each client
    // Broadcast(event, message)
    server.Broadcast("hello", "hello world")
  • Broadcast message to specific room
    // Broadcast(event, message, room)
    server.Broadcast("chat", "Hi!", "coffee meets")
  • Broadcast message to each server
    // BroadcastToServer(message)
    server.BroadcastToServer("Hello!")
  • Event Listen
    // On(event, func)
    server.On("onConnect", func(c ws.Client) error {
        // do something
    })
  • Receive message from other server
    // On(event, func)
    server.On("BroadcastToServer", func(msg string) {
        // do something
    })
Client
  • Event Listen
    // On(event, func)
    client.On("hello", func(msg string) {
        // do something
    })

    client.On("onDisconnect", func(msg string) {
        // do something
    })

    client.On("onError", func(e error) {
        // do something
    })
  • Join & Leave room
    // Join(room) & Leave(room)
    client.Join("yeeeee")

    client.Leave("yeeeee")
  • Emit message to specific room
    // To(room, event, message)
    client.To("yeeeee", "hello", "hello world")
  • Emit message
    // Emit(event, message)
    client.Emit("hello", "hello world")

Todo

  • Testing
  • Go doc

Show your support

Give a ⭐️ if this project helped you!

License

This Project is MIT license.

gorilla/webSocket BSD-2-Clause

go-redis/redis BSD-2-Clause

uuid BSD-3-Clause


This README was generated with ❤️ by readme-md-generator

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
	Context map[string]interface{}
	// contains filtered or unexported fields
}

Client Structure

func (*Client) Emit

func (c *Client) Emit(event string, message string, room ...string)

Emit Message

func (*Client) Join

func (c *Client) Join(room string)

Join Room

func (*Client) Leave

func (c *Client) Leave(room string)

Leave Room

func (*Client) On

func (c *Client) On(event string, handler interface{})

On Event Listener

func (*Client) To

func (c *Client) To(room string, event string, message string)

To Emit Message on Specific Room

type Server

type Server struct {
	sync.Mutex
	// contains filtered or unexported fields
}

Server Struct

func NewServer

func NewServer(redisClient *redis.Client) *Server

NewServer call to Init WebSocket Server

func (*Server) Broadcast

func (s *Server) Broadcast(event string, message string, room ...string)

Broadcast Message to Each Client From Server

func (*Server) BroadcastToServer added in v0.6.4

func (s *Server) BroadcastToServer(msg string)

BroadcastToServer for sending msg to each server

func (*Server) NewClient

func (s *Server) NewClient(conn *websocket.Conn, context map[string]interface{}) *Client

NewClient When New Client Connected

func (*Server) On added in v0.6.0

func (s *Server) On(event string, handler interface{})

On Event Listener

func (*Server) ServeHTTP added in v0.6.0

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request, context ...map[string]interface{})

func (*Server) SetReadLimit added in v0.6.5

func (s *Server) SetReadLimit(limit int64)

SetReadLimit sets the maximum size in bytes for a message read from the peer.

Directories

Path Synopsis
example
gin

Jump to

Keyboard shortcuts

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