Glue - Robust Go and Javascript Socket Library (Alternative to Socket.io)

Related tags

Messaging glue
Overview

Glue - Robust Go and Javascript Socket Library

GoDoc Go Report Card Join the chat at https://gitter.im/desertbit/glue

Glue is a real-time bidirectional socket library. It is a clean, robust and efficient alternative to socket.io. This library is designed to connect webbrowsers with a go-backend in a simple way. It automatically detects supported socket layers and chooses the most suitable one. This library handles automatic reconnections on disconnections and handles caching to bridge those disconnections. The server implementation is thread-safe and stable. The API is fixed and there won't be any breaking API changes.

Socket layers

Currently two socket layers are supported:

  • WebSockets - This is the primary option. They are used if the webbrowser supports WebSockets defined by RFC 6455.
  • AjaxSockets - This socket layer is used as a fallback mode.

Support

Feel free to contribute to this project. Please check the TODO file for more information.

Install

Client

The client javascript Glue library is located in client/dist/glue.js.

You can use bower to install the client library:

bower install --save glue-socket

Server

Get the source and start hacking.

go get github.com/desertbit/glue

Import it with:

import "github.com/desertbit/glue"

Documentation

Client - Javascript Library

A simple call to glue() without any options will establish a socket connection to the same host. A glue socket object is returned.

// Create and connect to the server.
// Optional pass a host string and options.
var socket = glue();

Optional Javascript options which can be passed to Glue:

var host = "https://foo.bar";

var opts = {
    // The base URL is appended to the host string. This value has to match with the server value.
    baseURL: "/glue/",

    // Force a socket type.
    // Values: false, "WebSocket", "AjaxSocket"
    forceSocketType: false,

    // Kill the connect attempt after the timeout.
    connectTimeout:  10000,

    // If the connection is idle, ping the server to check if the connection is stil alive.
    pingInterval:           35000,
    // Reconnect if the server did not response with a pong within the timeout.
    pingReconnectTimeout:   5000,

    // Whenever to automatically reconnect if the connection was lost.
    reconnect:          true,
    reconnectDelay:     1000,
    reconnectDelayMax:  5000,
    // To disable set to 0 (endless).
    reconnectAttempts:  10,

    // Reset the send buffer after the timeout.
    resetSendBufferTimeout: 10000
};

// Create and connect to the server.
// Optional pass a host string and options.
var socket = glue(host, opts);

The glue socket object has following public methods:

// version returns the glue socket protocol version.
socket.version();

// type returns the current used socket type as string.
// Either "WebSocket" or "AjaxSocket".
socket.type();

// state returns the current socket state as string.
// Following states are available:
//  - "disconnected"
//  - "connecting"
//  - "reconnecting"
//  - "connected"
socket.state();

// socketID returns the socket's ID.
// This is a cryptographically secure pseudorandom number.
socket.socketID();

// send a data string to the server.
// One optional discard callback can be passed.
// It is called if the data could not be send to the server.
// The data is passed as first argument to the discard callback.
// returns:
//  1 if immediately send,
//  0 if added to the send queue and
//  -1 if discarded.
socket.send(data, discardCallback);

// onMessage sets the function which is triggered as soon as a message is received.
socket.onMessage(f);

// on binds event functions to events.
// This function is equivalent to jQuery's on method syntax.
// Following events are available:
//  - "connected"
//  - "connecting"
//  - "disconnected"
//  - "reconnecting"
//  - "error"
//  - "connect_timeout"
//  - "timeout"
//  - "discard_send_buffer"
socket.on();

// Reconnect to the server.
// This is ignored if the socket is not disconnected.
// It will reconnect automatically if required.
socket.reconnect();

// close the socket connection.
socket.close();

// channel returns the given channel object specified by name
// to communicate in a separate channel than the default one.
socket.channel(name);

A channel object has following public methods:

// onMessage sets the function which is triggered as soon as a message is received.
c.onMessage(f);

// send a data string to the channel.
// One optional discard callback can be passed.
// It is called if the data could not be send to the server.
// The data is passed as first argument to the discard callback.
// returns:
//  1 if immediately send,
//  0 if added to the send queue and
//  -1 if discarded.
c.send(data, discardCallback);

Server - Go Library

Check the Documentation at GoDoc.org.

Use a custom HTTP multiplexer

If you choose to use a custom HTTP multiplexer, then it is possible to deactivate the automatic HTTP handler registration of glue.

// Create a new glue server without configuring and starting the HTTP server.
server := glue.NewServer(glue.Options{
    HTTPSocketType: HTTPSocketTypeNone,
})

//...

The glue server implements the ServeHTTP method of the HTTP Handler interface of the http package. Use this to register the glue HTTP handler with a custom multiplexer. Be aware, that the URL of the custom HTTP handler has to match with the glue HTTPHandleURL options string.

Reading data

Data has to be read from the socket and each channel. If you don't require to read data from the socket or a channel, then discard received data with the DiscardRead() method. If received data is not discarded, then the read buffer will block as soon as it is full, which will also block the keep-alive mechanism of the socket. The result would be a closed socket...

// ...

// Discard received data from the main socket channel.
// Hint: Channels have to be discarded separately.
s.DiscardRead()

// ...

// Create a channel.
c := s.Channel("golang")

// Discard received data from a channel.
c.DiscardRead()

Bind custom values to a socket

The socket.Value interface is a placeholder for custom data.

type CustomValues struct {
    Foo string
    Bar int
}

// ...

s.Value = &CustomValues{
    Foo: "Hello World",
    Bar: 900,
}

// ...

v, ok := s.Value.(*CustomValues)
if !ok {
    // Handle error
    return
}

Channels

Channels are separate communication channels from the client to the server of a single socket connections. Multiple separate communication channels can be created:

Server:

// ...

// Create a channel.
c := s.Channel("golang")

// Set the channel on read event function.
c.OnRead(func(data string) {
    // ...
})

// Write to the channel.
c.Write("Hello Gophers!")

Client:

var c = socket.channel("golang");

c.onMessage(function(data) {
    console.log(data);
});

c.send("Hello World");

Broadcasting Messages

With Glue it is easy to broadcast messages to multiple clients. The Glue Server keeps track of all active connected client sessions. You can make use of the server Sockets, GetSocket or OnNewSocket methods to implement broadcasting.

Example

This socket library is very straightforward to use. Check the sample directory for more examples.

Client

<script>
    // Create and connect to the server.
    // Optional pass a host string and options.
    var socket = glue();

    socket.onMessage(function(data) {
        console.log("onMessage: " + data);

        // Echo the message back to the server.
        socket.send("echo: " + data);
    });


    socket.on("connected", function() {
        console.log("connected");
    });

    socket.on("connecting", function() {
        console.log("connecting");
    });

    socket.on("disconnected", function() {
        console.log("disconnected");
    });

    socket.on("reconnecting", function() {
        console.log("reconnecting");
    });

    socket.on("error", function(e, msg) {
        console.log("error: " + msg);
    });

    socket.on("connect_timeout", function() {
        console.log("connect_timeout");
    });

    socket.on("timeout", function() {
        console.log("timeout");
    });

    socket.on("discard_send_buffer", function() {
        console.log("some data could not be send and was discarded.");
    });
</script>

Server

Read data from the socket with a read event function. Check the sample directory for other ways of reading data from the socket.

import (
    "log"
    "net/http"

    "github.com/desertbit/glue"
)

func main() {
    // Create a new glue server.
    server := glue.NewServer(glue.Options{
        HTTPListenAddress: ":8080",
    })

    // Release the glue server on defer.
    // This will block new incoming connections
    // and close all current active sockets.
    defer server.Release()

    // Set the glue event function to handle new incoming socket connections.
    server.OnNewSocket(onNewSocket)

    // Run the glue server.
    err := server.Run()
    if err != nil {
        log.Fatalf("Glue Run: %v", err)
    }
}

func onNewSocket(s *glue.Socket) {
    // Set a function which is triggered as soon as the socket is closed.
    s.OnClose(func() {
        log.Printf("socket closed with remote address: %s", s.RemoteAddr())
    })

    // Set a function which is triggered during each received message.
    s.OnRead(func(data string) {
        // Echo the received data back to the client.
        s.Write(data)
    })

    // Send a welcome string to the client.
    s.Write("Hello Client")
}

Similar Go Projects

  • go-socket.io - socket.io library for golang, a realtime application framework.
Issues
  • Add MIT dual licence

    Add MIT dual licence

    I'd like to use this in a project, but there are several issues related to the GPL that could cause trouble when the js code is distributed in a web app. Would it be possible to add a dual MIT license to this code?

    opened by conejo 7
  • Update socket.go

    Update socket.go

    Remove dirty hack, because gorilla websocket does not use 1001 error code

    It was used here:

        case CloseMessage:
            c.WriteControl(CloseMessage, []byte{}, time.Now().Add(writeWait))
            closeCode := CloseNoStatusReceived
            closeText := ""
            if len(payload) >= 2 {
                closeCode = int(binary.BigEndian.Uint16(payload))
                closeText = string(payload[2:])
            }
            return noFrame, &CloseError{Code: closeCode, Text: closeText}
        }
    
    opened by ZloyDyadka 4
  • Nix jQuery Dependency

    Nix jQuery Dependency

    This is a great, no nonsense, library. Thanks for creating it! With that said can you possibly entertain the idea of getting rid of the jquery dependency? Jquery is great and all but it's too much fluff when all you need is the ajax portion. At least if continuing to use a dependency maybe change to axios or fetch or something that is specifically created for the job needed.

    Thanks!

    opened by u382514 3
  • "github.com/Sirupsen/logrus" organization name renamed to lowercase

    The sirupsen organization has been renamed to lowercase "github.com/sirupsen/logrus". This causes issues when trying to resolve this project's dependencies.

    Imports should be search-replaced to use lower-case "sirupsen"

    opened by smyrman 2
  • added SetLogOutput and prefixed formatter

    added SetLogOutput and prefixed formatter

    SetLogOutput allows adding an io.Writer as the loggers output destination. This is useful for logging into a file or into a stream multiplexer. The prefixed formatter allows adding prefixes to log messages, which is helpful for debugging. Also it has a very nice output.

    opened by dreadl0ck 2
  • Cannot install on Go 1.8

    Cannot install on Go 1.8

    Trying to set it up on OSX 10.11.6, Go version 1.8 and getting error:

    go get github.com/desertbit/glue
    # github.com/desertbit/glue/backend/sockets/websocket
    glue/backend/sockets/websocket/socket.go:156: undefined: websocket.CloseError
    

    Tried it on 1.7.4 on a Ubuntu 14.04 VPS and it installed without problem.

    Maybe it's a problem due to the package having the same name as gorilla/websocket package?

    opened by ripexz 1
  • Closes #14 Update license to dual MIT and GPL3

    Closes #14 Update license to dual MIT and GPL3

    I've based this dual license off of the libpng dual BSD GPL license: https://raw.githubusercontent.com/glennrp/libpng/libpng16/contrib/gregbook/LICENSE

    Please feel free to make or request modifications!

    opened by ameliabradley 0
  • Add a Gitter chat badge to README.md

    Add a Gitter chat badge to README.md

    desertbit/glue now has a Chat Room on Gitter

    @m4ng0squ4sh has just created a chat room. You can visit it here: https://gitter.im/desertbit/glue.

    This pull-request adds this badge to your README.md:

    Gitter

    If my aim is a little off, please let me know.

    Happy chatting.

    PS: Click here if you would prefer not to receive automatic pull-requests from Gitter in future.

    opened by gitter-badger 0
  • baseUrl Value

    baseUrl Value

    When I changed the base 'baseURL' on the js side and http handle functions pattern on the go side, js client can not connect to server. Its about the string length. It can not connect to server if string length longer than 4.

    opened by ProgramYazar 2
  • Split / Subrepo Javascript Client

    Split / Subrepo Javascript Client

    Hi,

    I was wondering if it would be possible to split out the client library so that I can then be published to NPM and other Javascript package management tools and the bought in as a modern dependency?

    Thanks.

    opened by bobbysciacchitano 2
Owner
DesertBit
DesertBit Projects
DesertBit
socket.io library for golang, a realtime application framework.

go-socket.io go-socket.io is library an implementation of Socket.IO in Golang, which is a realtime application framework. Current this library support

Googol Lee 4.7k Jul 1, 2022
šŸ‡ Easy to use socket lib for Golang

Hare Sockets ?? Hare is a user-friendly lib for sockets in Golang. You can send and listen to TCP connections with a few lines of code. Contents Insta

Leonardo Lima 48 Jul 2, 2022
RapidMQ is a pure, extremely productive, lightweight and reliable library for managing of the local messages queue

RapidMQ RapidMQ is a pure, extremely productive, lightweight and reliable library for managing of the local messages queue in the Go programming langu

Vadim Shakun 63 Apr 24, 2022
Sarama is a Go library for Apache Kafka 0.8, and up.

sarama Sarama is an MIT-licensed Go client library for Apache Kafka version 0.8 (and later). Getting started API documentation and examples are availa

Shopify 8.7k Jun 30, 2022
GTA(Go Task Async) is a lightweight reliable asynchronous task and transaction message library for Golang

GTA (Go Task Async) is a lightweight and reliable asynchronous task and transaction message library for by golang.

Kevin Su 12 Jun 4, 2022
Producer x Consumer example using Kafka library and Go.

Go - Kafka - Example Apache Kafka Commands First of all, run the docker-compose docker-compose up, than run docker exec -it kafka_kafka_1 bash Topics

Roberto Morel 0 Dec 8, 2021
Go library for dealing with Ademco and Contact-ID messages

Ademco For Go A lightweight golang library for dealing with Contact-ID and Ademco messaging formats. Installation install via go get $ go get github.c

Josh Burns 0 Jan 11, 2022
RES Service protocol library for Go

RES Service for Go Synchronize Your Clients Go package used to create REST, real time, and RPC APIs, where all your reactive web clients are synchroni

Samuel JirƩnius 58 May 28, 2022
golang client library to Viessmann Vitotrol web service

Package go-vitotrol provides access to the Viessmannā„¢ Vitotrolā„¢ cloud API for controlling/monitoring boilers. See https://www.viessmann.com/app_vitoda

Maxime SoulƩ 18 Jun 23, 2022
golang long polling library. Makes web pub-sub easy via HTTP long-poll server :smiley: :coffee: :computer:

golongpoll Golang long polling library. Makes web pub-sub easy via an HTTP long-poll server. New in v1.1 Deprecated CreateManager and CreateCustomMana

J Cuga 600 Jun 23, 2022
A library for scheduling when to dispatch a message to a channel

gosd go-schedulable-dispatcher (gosd), is a library for scheduling when to dispatch a message to a channel. Implementation The implementation provides

Alexander Sniffin 19 Jan 23, 2022
A dead simple Go library for sending notifications to various messaging services.

A dead simple Go library for sending notifications to various messaging services. About Notify arose from my own need for one of my api server running

Niko Kƶser 1.2k Jun 28, 2022
A user friendly RabbitMQ library written in Golang.

TurboCookedRabbit A user friendly RabbitMQ library written in Golang to help use streadway/amqp. Based on my work found at CookedRabbit. Work Recently

Tristan (HouseCat) Hyams 99 Jun 10, 2022
franz-go contains a high performance, pure Go library for interacting with Kafka from 0.8.0 through 2.7.0+. Producing, consuming, transacting, administrating, etc.

franz-go - Apache Kafka client written in Go Franz-go is an all-encompassing Apache Kafka client fully written Go. This library aims to provide every

Travis Bischel 669 Jun 24, 2022
Go client library SDK for Ably realtime messaging service

Ably Go A Go client library for www.ably.io, the realtime messaging service. Installation ~ $ go get -u github.com/ably/ably-go/ably Feature support T

Ably Realtime - our client library SDKs and libraries 50 Jun 21, 2022
Cluster extensions for Sarama, the Go client library for Apache Kafka 0.9

Cluster extensions for Sarama, the Go client library for Apache Kafka 0.9 (and later).

Black Square Media 1k Jun 15, 2022
Apache Pulsar Go Client Library

Apache Pulsar Go Client Library A Go client library for the Apache Pulsar project. Goal This projects is developing a pure-Go client library for Pulsa

The Apache Software Foundation 457 Jun 22, 2022
kafka watcher for casbin library

Casbin Kafka Watcher Casbin watcher for kafka This watcher library will enable users to dynamically change casbin policies through kakfa messages Infl

Aruna Prabashwara 3 May 8, 2021
Transpiled version of the CCXT exchange library to Go (Golang)

CCXT Go Transpiled CCXT exchange library from their original JavaScript source to Go (Golang). Features support 100+ cryptocurrency exchanges with a u

null 44 Jul 1, 2022