sockets

package module
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2022 License: MIT Imports: 10 Imported by: 0

README

   ____         __       __    
  / __/__  ____/ /_____ / /____
 _\ \/ _ \/ __/  '_/ -_) __(_-<
/___/\___/\__/_/\_\\__/\__/___/               

Build Status

Sockets is a websocket framework based on gorilla/websocket providing a simple way to write real-time apps.

Features

  • Room & Room Channel support.
  • Easily broadcast to Rooms/Channels.
  • Multiple connections under the same username.

Installation

go get github.com/syleron/sockets

Simple client usage

package main

import (
    "fmt"
    sktsClient "github.com/syleron/sockets/client"
    "github.com/syleron/sockets/common"
    "time"
)

type SocketHandler struct{}

func (h *SocketHandler) NewConnection() {
    // Do something when a new connection comes in
    fmt.Println("> Connection established")
}

func (h *SocketHandler) ConnectionClosed() {
    // Do something when a connection is closed
    fmt.Println("> Connection closed")
}

func (h *SocketHandler) NewClientError(err error) {
    // Do something when a connection error is found
    fmt.Printf("> DEBUG %v\n", err)
}

func main() {
    // Create our websocket client
    client, err := sktsClient.Dial("127.0.0.1:5000", false, &SocketHandler{})
    if err != nil {
        panic(err)
    }
    defer client.Close()

    // Define event handler
    client.HandleEvent("pong", pong)

    payload := &common.Message{
        EventName: "ping",
    }

    // Send our initial request
    client.Emit(payload)

    // Send another
    count := 0
    for range time.Tick(5 * time.Second) {
        if count < 1 {
            client.Emit(payload)
            count++
        } else {
            return
        }
    }
}

func pong(msg *common.Message) {
    fmt.Println("> Recieved WSKT 'pong'")
}

Simple server usage

package main

import (
    "fmt"
    "github.com/syleron/sockets"
    "github.com/syleron/sockets/common"
    "github.com/gin-gonic/gin"
)

type SocketHandler struct {}

func (h *SocketHandler) NewConnection(ctx *sockets.Context) {
    // Do something when a new connection comes in
    fmt.Println("> Connection established")
}

func (h *SocketHandler) ConnectionClosed(ctx *sockets.Context) {
    // Do something when a connection is closed
    fmt.Println("> Connection closed")
}

func main () {
    // Setup socket server
    sockets := sockets.New(&SocketHandler{})

    // Register our events
    sockets.HandleEvent("ping", ping)

    // Set our gin release mode
    gin.SetMode(gin.ReleaseMode)

    // Setup router
    router := gin.Default()

    // Setup websockets
    router.GET("/ws", func(c *gin.Context) {
        sockets.HandleConnection(c.Writer, c.Request)
    })

    fmt.Println("> Sockets server started. Waiting for connections..")

    // Start server
    router.Run(":5000")
}

func ping(msg *common.Message, ctx *sockets.Context) {
    fmt.Println("> Recieved WSKT 'ping' responding with 'pong'")
    ctx.Emit(&common.Message{
        EventName: "pong",
    })
}

Projects using sockets

  • Yudofu: Anime social network

Note: If your project is not listed here, let us know! :)

Licence

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EventHandler

func EventHandler(msg *common.Message, ctx *Context)

Types

type Broadcast

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

type Connection

type Connection struct {
	UUID   string
	Conn   *websocket.Conn
	Status bool  `json:"status"`
	Room   *Room `json:"room"`
	Data   map[string]interface{}
	*Session
}

func NewConnection added in v1.4.0

func NewConnection() *Connection

func (*Connection) AddSession added in v1.4.0

func (c *Connection) AddSession(session *Session)

func (*Connection) ClearSession added in v1.4.0

func (c *Connection) ClearSession(session *Session)

func (*Connection) Emit added in v1.4.0

func (c *Connection) Emit(msg interface{}) error

func (*Connection) GetData added in v1.7.0

func (c *Connection) GetData(key string) interface{}

func (*Connection) SetData added in v1.7.0

func (c *Connection) SetData(key string, value interface{})

type Context

type Context struct {
	*Connection
	UUID string
}

type DataHandler

type DataHandler interface {
	// NewConnection Client connected handler
	NewConnection(ctx *Context)
	// ConnectionClosed Client disconnect handler
	ConnectionClosed(ctx *Context)
}

type EventFunc

type EventFunc func(msg *common.Message, ctx *Context)

type Room

type Room struct {
	Name    string `json:"name"`
	Channel string `json:"channel"`
}

type Session added in v1.4.0

type Session struct {
	Username string

	sync.Mutex
	// contains filtered or unexported fields
}

func (*Session) Emit added in v1.4.0

func (s *Session) Emit(msg *common.Message)

func (*Session) HasSession added in v1.6.0

func (s *Session) HasSession() bool

type Sockets

type Sockets struct {
	Connections map[string]*Connection
	Sessions    map[string]*Session

	sync.Mutex
	// contains filtered or unexported fields
}

func New

func New(handler DataHandler) *Sockets

func (*Sockets) Broadcast added in v1.3.0

func (s *Sockets) Broadcast(event string, data, options interface{})

func (*Sockets) BroadcastToRoom

func (s *Sockets) BroadcastToRoom(roomName, event string, data interface{}, ctx *Context)

func (*Sockets) BroadcastToRoomChannel

func (s *Sockets) BroadcastToRoomChannel(roomName, channelName, event string, data interface{}, ctx *Context)

func (*Sockets) CheckIfSessionExists added in v1.4.0

func (s *Sockets) CheckIfSessionExists(username string) bool

func (*Sockets) Close

func (s *Sockets) Close()

func (*Sockets) GetUserRoom

func (s *Sockets) GetUserRoom(username, uuid string) (string, error)

func (*Sockets) HandleConnection

func (s *Sockets) HandleConnection(w http.ResponseWriter, r *http.Request) error

func (*Sockets) HandleEvent

func (s *Sockets) HandleEvent(pattern string, handler EventFunc)

func (*Sockets) InterruptHandler

func (s *Sockets) InterruptHandler()

func (*Sockets) JoinRoom

func (s *Sockets) JoinRoom(room, uuid string) error

func (*Sockets) JoinRoomChannel

func (s *Sockets) JoinRoomChannel(channel, uuid string) error

func (*Sockets) LeaveRoom

func (s *Sockets) LeaveRoom(uuid string)

func (*Sockets) NewUserSession added in v1.4.0

func (s *Sockets) NewUserSession(username string, conn *Connection)

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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