All Projects → philippseith → signalr

philippseith / signalr

Licence: MIT license
SignalR server and client in go

Programming Languages

go
31211 projects - #10 most used programming language
HTML
75241 projects
typescript
32286 projects
Makefile
30231 projects

Projects that are alternatives of or similar to signalr

signalr-client
SignalR client library built on top of @aspnet/signalr. This gives you more features and easier to use.
Stars: ✭ 48 (-30.43%)
Mutual labels:  signalr, signalr-client
TypedSignalR.Client
C# Source Generator to Create Strongly Typed SignalR Client.
Stars: ✭ 16 (-76.81%)
Mutual labels:  signalr, signalr-client
Sapphiredb
SapphireDb Server, a self-hosted, easy to use realtime database for Asp.Net Core and EF Core
Stars: ✭ 326 (+372.46%)
Mutual labels:  server-sent-events, signalr
SignalR-Core-SqlTableDependency
Shows how the new SignalR Core works with hubs and sockets, also how it can integrate with SqlTableDependency API.
Stars: ✭ 36 (-47.83%)
Mutual labels:  signalr, signalr-client
Azure Signalr
Azure SignalR Service SDK for .NET
Stars: ✭ 137 (+98.55%)
Mutual labels:  server-sent-events, signalr
urlpack
Pure JavaScript toolkit for data URLs (MessagePack, Base58 and Base62)
Stars: ✭ 51 (-26.09%)
Mutual labels:  messagepack
GAPITA
An anonymous and random chat messaging for talking to strangers! (Using SignalR C# and TypeScript)
Stars: ✭ 55 (-20.29%)
Mutual labels:  signalr
pokeR
Planning poker with SignalR
Stars: ✭ 37 (-46.38%)
Mutual labels:  signalr
WebApiClient.Extensions
WebApiClient项目的第三方扩展:Autofac、DependencyInjection、HttpClientFactory、SteeltoeOSS.Discovery、MessagePack、Protobuf、Json-Rpc
Stars: ✭ 73 (+5.8%)
Mutual labels:  messagepack
msgpack-perl
MessagePack serializer implementation for Perl / msgpack.org[Perl]
Stars: ✭ 48 (-30.43%)
Mutual labels:  messagepack
fetch-event-source
A better API for making Event Source requests, with all the features of fetch()
Stars: ✭ 120 (+73.91%)
Mutual labels:  server-sent-events
IEvangelist.VideoChat
Imagine two Twilio SDKs, ASP.NET Core/C#, Angular/TypeScript, SignalR, etc... Yeah, amazing!
Stars: ✭ 66 (-4.35%)
Mutual labels:  signalr
live-share-editor
ソースコードをリアルタイムで共有できるオンラインエディタ
Stars: ✭ 15 (-78.26%)
Mutual labels:  signalr
iShop
A shopping website using ASP.net Core 2.0, EF Core 2.0 and Angular 5
Stars: ✭ 17 (-75.36%)
Mutual labels:  signalr
hilo
Home Assistant Hilo Integration via HACS
Stars: ✭ 72 (+4.35%)
Mutual labels:  signalr-client
TraceHub
Centralized and distributed logging for Web applications and services, extending System.Diagnostics and Essential.Diagnostics, providing structured tracing and logging withou needing to change 1 line of your application codes
Stars: ✭ 22 (-68.12%)
Mutual labels:  signalr
msgpack
🐴 Pure Pony implementation of the MessagePack serialization format. msgpack.org[Pony]
Stars: ✭ 31 (-55.07%)
Mutual labels:  messagepack
ReaLocate
ASP.NET MVC 5 Real Estate Application
Stars: ✭ 18 (-73.91%)
Mutual labels:  signalr
online-training
Online Training website using ASP.Net Core 2.0 & Angular 4
Stars: ✭ 26 (-62.32%)
Mutual labels:  signalr
ngx-signalr-hubservice
Makes using SignalR in Angular 2/4 easy
Stars: ✭ 24 (-65.22%)
Mutual labels:  signalr

SignalR

Actions Status codecov PkgGoDev

SignalR is an open-source library that simplifies adding real-time web functionality to apps. Real-time web functionality enables server-side code to push content to clients instantly.

Historically it was tied to ASP.NET Core but the protocol is open and implementable in any language.

This repository contains an implementation of a SignalR server and a SignalR client in go. The implementation is based on the work of David Fowler at https://github.com/davidfowl/signalr-ports. Client and server support transport over WebSockets, Server Sent Events and raw TCP. Protocol encoding in JSON and MessagePack is fully supported.

Install

With a correctly configured Go toolchain:

go get -u github.com/philippseith/signalr

Getting Started

SignalR uses a signalr.HubInterface instance to anchor the connection on the server and a javascript HubConnection object to anchor the connection on the client.

Server side

Implement the HubInterface

The easiest way to implement the signalr.HubInterface in your project is to declare your own type and embed signalr.Hub which implements that interface and will take care of all the signalr plumbing. You can call your custom type anything you want so long as it implements the signalr.HubInterface interface.

package main

import "github.com/philippseith/signalr"

type AppHub struct {
    signalr.Hub
}

Add functions with your custom hub type as a receiver.

func (h *AppHub) SendChatMessage(message string) {
    h.Clients().All().Send("chatMessageReceived", message)
}

These functions must be public so that they can be seen by the signalr server package but can be invoked client-side as lowercase message names. We'll explain setting up the client side in a moment, but as a preview, here's an example of calling our AppHub.SendChatMessage(...) method from the client:

    // javascript snippet invoking that AppHub.Send method from the client
    connection.invoke('sendChatMessage', val);

The signalr.HubInterface contains a pair of methods you can implement to handle connection and disconnection events. signalr.Hub contains empty implementations of them to satisfy the interface, but you can "override" those defaults by implementing your own functions with your custom hub type as a receiver:

func (c *chat) OnConnected(connectionID string) {
    fmt.Printf("%s connected\n", connectionID)
}

func (c *chat) OnDisconnected(connectionID string) {
   fmt.Printf("%s disconnected\n", connectionID)
}

Serve with http.ServeMux

import (
    "net/http"
	
    "github.com/philippseith/signalr"
)

func runHTTPServer() {
    address := 'localhost:8080'
    
    // create an instance of your hub
    hub := AppHub{}
	
    // build a signalr.Server using your hub
    // and any server options you may need
    server, _ := signalr.NewServer(context.TODO(),
        signalr.SimpleHubFactory(hub)
        signalr.KeepAliveInterval(2*time.Second),
        signalr.Logger(kitlog.NewLogfmtLogger(os.Stderr), true))
    )
    
    // create a new http.ServerMux to handle your app's http requests
    router := http.NewServeMux()
    
    // ask the signalr server to map it's server
    // api routes to your custom baseurl
    server.MapHTTP(signalr.WithHTTPServeMux(router), "/chat")

    // in addition to mapping the signalr routes
    // your mux will need to serve the static files
    // which make up your client-side app, including
    // the signalr javascript files. here is an example
    // of doing that using a local `public` package
    // which was created with the go:embed directive
    // 
    // fmt.Printf("Serving static content from the embedded filesystem\n")
    // router.Handle("/", http.FileServer(http.FS(public.FS)))
    
    // bind your mux to a given address and start handling requests
    fmt.Printf("Listening for websocket connections on http://%s\n", address)
    if err := http.ListenAndServe(address, router); err != nil {
        log.Fatal("ListenAndServe:", err)
    }
}

Client side: JavaScript/TypeScript

Grab copies of the signalr scripts

Microsoft has published the client-side libraries as a node package with embedded typescript annotations: @microsoft/signalr.

You can install @microsoft/signalr through any node package manager:

package manager command
npm npm install @microsoft/signalr@latest
yarn yarn add @microsoft/signalr@latest
LibMan libman install @microsoft/signalr@latest -p unpkg -d wwwroot/js/signalr --files dist/browser/signalr.js --files dist/browser/signalr.min.js --files dist/browser/signalr.map.js
none you can download the version we are using in our chatsample from here (the minified version is here)

Use a HubConnection to connect to your server Hub

How you format your client UI is going to depend on your application use case but here is a simple example. It illustrates the basic steps of connecting to your server hub:

  1. import the signalr.js library (or signalr.min.js);

  2. create a connection object using the HubConnectionBuilder;

  3. bind events

    • UI event handlers can use connection.invoke(targetMethod, payload) to send invoke functions on the server hub;
    • connection event handlers can react to the messages sent from the server hub;
  4. start your connection

<html>
<body>
    <!-- you may want the content you send to be dynamic -->
    <input type="text" id="message" />
    
    <!-- you may need a trigger to initiate the send -->
    <input type="button" value="Send" id="send" />
    
    <!-- you may want some container to display received messages -->
    <ul id="messages">
    </ul>

    <!-- 1. you need to import the signalr script which provides
            the HubConnectionBuilder and handles the connection
            plumbing.
    -->
    <script src="js/signalr.js"></script>
    <script>
    (async function () {
        // 2. use the signalr.HubConnectionBuilder to build a hub connection
        //    and point it at the baseurl which you configured in your mux
        const connection = new signalR.HubConnectionBuilder()
                .withUrl('/chat')
                .build();

        // 3. bind events:
        //    - UI events can invoke (i.e. dispatch to) functions on the server hub
        document.getElementById('send').addEventListener('click', sendClicked);
        //    - connection events can handle messages received from the server hub
        connection.on('chatMessageReceived', onChatMessageReceived);

        // 4. call start to initiate the connection and start streaming events
        //    between your server hub and your client connection
        connection.start();
        
        // that's it! your server and client should be able to communicate
        // through the signalr.Hub <--> connection pipeline managed by the
        // signalr package and client-side library.
        
        // --------------------------------------------------------------------
       
        // example UI event handler
        function sendClicked() {
            // prepare your target payload
            const msg = document.getElementById('message').value;
            if (msg) {
                // call invoke on your connection object to dispatch
                // messages to the server hub with two arguments:
                // -  target: name of the hub func to invoke
                // - payload: the message body
                // 
                const target = 'sendChatMessage';
                connection.invoke(target, msg);
            }
        }

        // example server event handler
        function onChatMessageReceived(payload) {
            // the payload is whatever was passed to the inner
            // clients' `Send(...)` method in your server-side
            // hub function.
           
            const li = document.createElement('li');
            li.innerText = payload;
            document.getElementById('messages').appendChild(li);
        }
    })();
    </script>
</body>
</html>

Client side: go

To handle callbacks from the server, create a receiver class which gets the server callbacks mapped to its methods:

type receiver struct {
	signalr.Hub
}

func (c *receiver) Receive(msg string) {
	fmt.Println(msg)
}

Receive gets called when the server does something like this:

hub.Clients().Caller().Send("receive", message)

The client itself might be used like that:

// Create a Connection (with timeout for the negotiation process)
creationCtx, _ := context.WithTimeout(ctx, 2 * time.Second)
conn, err := signalr.NewHTTPConnection(creationCtx, address)
if err != nil {
    return err
}
// Create the client and set a receiver for callbacks from the server
client, err := signalr.NewClient(ctx, conn,
	signalr.WithConnection(conn),
	signalr.WithReceiver(receiver))
if err != nil {
    return err
}
// Start the client loop
c.Start()
// Do some client work
ch := <-c.Invoke("update", data)
// ch gets the result of the update operation

Debugging

Server, Client and the protocol implementations are able to log most of their operations. The logging option is disabled by default in all tests. To configure logging, edit the testLogConf.json file:

{
  "Enabled": false,
  "Debug": false
}
  • If Enabled is set to true, the logging will be enabled. The tests will log to os.Stderr.
  • If Debug ist set to true, the logging will be more detailed.
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].