sockets

package module
v1.5.2 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 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.

ATTENTION: As of the latest release, I've removed JWT authentication as I believe this is best handled by specific project implementations rather than this project.

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() {
    // Generate JWT token
    jwt, err := common.GenerateJWT("steve", "SuperSecretKey")
    if err != nil {
        panic(err)
    }

    // Create our websocket client
    client, err := sktsClient.Dial("127.0.0.1:5000", jwt, 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("SuperSecretKey", &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

Overview

* MIT License

Copyright (c) 2018-2019 Andrew Zak <andrew@linux.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

* MIT License

Copyright (c) 2018-2019 Andrew Zak <andrew@linux.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

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"`
	*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

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)

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
* MIT License Copyright (c) 2018-2019 Andrew Zak <andrew@linux.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* MIT License Copyright (c) 2018-2019 Andrew Zak <andrew@linux.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* MIT License Copyright (c) 2018 Andrew Zak <andrew@linux.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* MIT License Copyright (c) 2018 Andrew Zak <andrew@linux.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
examples
client
* MIT License Copyright (c) 2018-2019 Andrew Zak <andrew@linux.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* MIT License Copyright (c) 2018-2019 Andrew Zak <andrew@linux.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
server
* MIT License Copyright (c) 2018-2019 Andrew Zak <andrew@linux.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* MIT License Copyright (c) 2018-2019 Andrew Zak <andrew@linux.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

Jump to

Keyboard shortcuts

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