gosocketio

package module
v0.0.0-...-c289471 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2025 License: MIT, MIT Imports: 16 Imported by: 0

README

GoSocketIO

GoDoc Go Report Card

GoSocketIO is a Socket.IO client and server library for Go, compatible with Socket.IO v3 and v4. This package allows you to build real-time, bidirectional communication applications with ease.

This library is based off the GoLang SocketIO Framework

This library was built with previous contributions by:

Features

  • Socket.IO v3 and v4 Compatible: Fully compatible with the latest versions of Socket.IO.
  • Extra Headers Support: Customize HTTP headers for WebSocket connections.
  • Event-based Architecture: Simplified event handling for connection, disconnection, and custom events.
  • Room Support: Easily broadcast messages to specific groups of clients.
  • Ping/Pong Mechanism: Built-in heartbeat mechanism to keep connections alive.

Installation

To install GoSocketIO, use go get:

go get github.com/TymekV/gosf-socketio

Usage

Server Example

Here’s a simple WebSocket server using GoSocketIO:

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/TymekV/gosf-socketio"
    "github.com/TymekV/gosf-socketio/transport"
)

func main() {
    server := gosocketio.NewServer(transport.GetDefaultWebsocketTransport())

    server.On(gosocketio.OnConnection, func(c *gosocketio.Channel) {
        fmt.Println("New client connected:", c.Id())
        c.Join("chat")
    })

    server.On(gosocketio.OnDisconnection, func(c *gosocketio.Channel) {
        fmt.Println("Client disconnected:", c.Id())
    })

    server.On("chat message", func(c *gosocketio.Channel, message string) {
        fmt.Printf("Received message from %s: %s\n", c.Id(), message)
        server.BroadcastTo("chat", "chat message", message)
    })

    http.Handle("/socket.io/", server)

    addr := "localhost:8080"
    fmt.Printf("Serving at %s...\n", addr)
    log.Fatal(http.ListenAndServe(addr, nil))
}

For more details, see the Server Example

Go Client Example

Here’s how you can create a Go client that connects to the server:

package main

import (
    "fmt"
    "log"
    "time"

    "github.com/TymekV/gosf-socketio"
    "github.com/TymekV/gosf-socketio/transport"
)

func main() {
    wsTransport := transport.GetDefaultWebsocketTransport()
    options := &gosocketio.Options{
        ExtraHeaders: []gosocketio.ExtraHeaders{
            {Key: "Content-Type", Value: "application/json"},
            {Key: "Authorization", Value: "Bearer YOUR_ACCESS_TOKEN"},
        },
        PingTimeout:  60 * time.Second,
        PingInterval: 30 * time.Second,
    }

    client, err := gosocketio.Dial("ws://localhost:8080/socket.io/?EIO=3&transport=websocket", wsTransport, options)
    if err != nil {
        log.Fatalf("Failed to connect to server: %v", err)
    }
    defer client.Close()

    client.On(gosocketio.OnConnection, func(c *gosocketio.Channel) {
        fmt.Println("Connected to server")
    })

    client.On(gosocketio.OnDisconnection, func(c *gosocketio.Channel) {
        fmt.Println("Disconnected from server")
    })

    client.On("chat message", func(c *gosocketio.Channel, message string) {
        fmt.Printf("Received message: %s\n", message)
    })

    err = client.Emit("chat message", "Hello, Server!")
    if err != nil {
        log.Printf("Failed to send message: %v", err)
    }

    select {}
}

For more details, see the Go Client Example

JavaScript Client Example

Here’s a simple JavaScript client using Socket.IO:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Socket.IO Client</title>
</head>
<body>
    <h1>WebSocket Chat</h1>
    <div id="chat">
        <ul id="messages"></ul>
    </div>
    <form id="form" action="">
        <input id="input" autocomplete="off" /><button>Send</button>
    </form>
    <script src="https://cdn.socket.io/4.0.1/socket.io.min.js"></script>
    <script>
        var socket = io('http://localhost:8080');

        socket.on('connect', function() {
            console.log('Connected to server');
        });

        socket.on('disconnect', function() {
            console.log('Disconnected from server');
        });

        socket.on('chat message', function(msg) {
            var item = document.createElement('li');
            item.textContent = msg;
            document.getElementById('messages').appendChild(item);
        });

        document.getElementById('form').addEventListener('submit', function(e) {
            e.preventDefault();
            var input = document.getElementById('input');
            socket.emit('chat message', input.value);
            input.value = '';
        });
    </script>
</body>
</html>

For more details, see the JavaScript Client Example

Contributing

We welcome contributions! Please check out the Contributing Guide for more details.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	OnConnection    = "connection"
	OnDisconnection = "disconnection"
	OnError         = "error"
)
View Source
const (
	HeaderForward = "X-Forwarded-For"
)

Variables

View Source
var (
	ErrorCallerNotFunc     = errors.New("f is not function")
	ErrorCallerMaxOneValue = errors.New("f should return not more than one value")
)
View Source
var (
	ErrorSendTimeout     = errors.New("Timeout")
	ErrorSocketOverflood = errors.New("Socket overflood")
)
View Source
var (
	ErrorServerNotSet       = errors.New("Server not set")
	ErrorConnectionNotFound = errors.New("Connection not found")
)
View Source
var (
	ErrorWaiterNotFound = errors.New("Waiter not found")
)
View Source
var ErrorWrongHeader = errors.New("Wrong header")

Functions

func GetUrl

func GetUrl(host string, port int, secure bool) string

GetUrl returns the ws/wss url by host and port

Types

type Channel

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

func (*Channel) Ack

func (c *Channel) Ack(method string, args interface{}, timeout time.Duration) (string, error)

Create ack packet based on given data and send it and receive response

func (*Channel) Amount

func (c *Channel) Amount(room string) int

Get amount of channels, joined to given room, using channel

func (*Channel) BroadcastTo

func (c *Channel) BroadcastTo(room, method string, args interface{})

func (*Channel) Close

func (c *Channel) Close()

Close current channel

func (*Channel) Emit

func (c *Channel) Emit(method string, args interface{}) error

Create packet based on given data and send it

func (*Channel) Id

func (c *Channel) Id() string

Get the ID of the current socket connection

func (*Channel) Ip

func (c *Channel) Ip() string

Get ip of socket client

func (*Channel) IsAlive

func (c *Channel) IsAlive() bool

Check if the Channel is still alive

func (*Channel) Join

func (c *Channel) Join(room string) error

Join this channel to given room

func (*Channel) Leave

func (c *Channel) Leave(room string) error

Remove this channel from given room

func (*Channel) List

func (c *Channel) List(room string) []*Channel

Get list of channels, joined to given room, using channel

func (*Channel) Request

func (c *Channel) Request() *http.Request

Get request

func (*Channel) RequestHeader

func (c *Channel) RequestHeader() http.Header

Get request header of this connection

type Client

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

func Dial

func Dial(url string, tr transport.Transport, opts *transport.Options) (*Client, error)

Dial connects to the server with the given options

func (*Client) Close

func (c *Client) Close()

Close client connection

func (*Client) On

func (m *Client) On(method string, f interface{}) error
type Header struct {
	Sid          string   `json:"sid"`
	Upgrades     []string `json:"upgrades"`
	PingInterval int      `json:"pingInterval"`
	PingTimeout  int      `json:"pingTimeout"`
}

Header represents engine.io header to send or receive

type Server

type Server struct {
	http.Handler
	// contains filtered or unexported fields
}

socket.io server instance

func NewServer

func NewServer(tr transport.Transport) *Server

Create new socket.io server

func (*Server) AddHeader

func (s *Server) AddHeader(name string, value string)

Add a header to HTTP responses

func (*Server) Amount

func (s *Server) Amount(room string) int

Get amount of channels, joined to given room, using server

func (*Server) AmountOfRooms

func (s *Server) AmountOfRooms() int64

Get amount of rooms with at least one channel(or sid) joined

func (*Server) AmountOfSids

func (s *Server) AmountOfSids() int64

Get amount of current connected sids

func (*Server) BroadcastTo

func (s *Server) BroadcastTo(room, method string, args interface{})

Broadcast message to all room channels

func (*Server) BroadcastToAll

func (s *Server) BroadcastToAll(method string, args interface{})

Broadcast to all clients

func (*Server) EnableCORS

func (s *Server) EnableCORS(domain string)

Enables CORS for all domains

func (*Server) GetChannel

func (s *Server) GetChannel(sid string) (*Channel, error)

Get channel by its sid

func (*Server) List

func (s *Server) List(room string) []*Channel

Get list of channels, joined to given room, using server

func (*Server) On

func (m *Server) On(method string, f interface{}) error

func (*Server) SendOpenSequence

func (s *Server) SendOpenSequence(c *Channel)

func (*Server) ServeHTTP

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

implements ServeHTTP function from http.Handler

func (*Server) SetupEventLoop

func (s *Server) SetupEventLoop(conn transport.Connection, remoteAddr string,
	r *http.Request)

Setup event loop for given connection

func (*Server) UpdateTransport

func (s *Server) UpdateTransport(tr transport.Transport)

Replaces the pre-configured transport

Directories

Path Synopsis
examples
example-server command

Jump to

Keyboard shortcuts

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