chevron_right
chevron_right
chevron_right
chevron_right
chevron_right
chevron_right
chevron_right
chevron_right

In order to integrate websocket in your application, you need to -

  • Create webscoket controller - create a class and inherits WebSocketController.
  • Use shinveri javascript library to establish communication between server and client.


Create Controller

class ChatController < Shivneri::WebSocketController


end

Similar to Http Controller - in order to make Websocket controller active, you need to assign it to routes.

Shivneri.routes = [{
    controller: ChatController,
    path:       "/chat",
}]


Websocket Client


Shivneri provides a javascript library - shivneri-ws-client-javascript to help you eastablish web socket communication.

var socket = new shivneriWsClient.Instance();
await socket.init(`<web-socket-url>`);


How to communicate


Shivneri follows pub sub model to communicate. A client or server subscribe to events and can emit events.

So whenever a server emit an event, it reaches to client and vice versa.

Subscribe an event in websocket controller

class ChatController < Shivneri::WebSocketController

    @[On("message")]
    def receive_message(data : String)

        # send message to caller
        clients.current.emit("message", "Received message is #{data}")

         # send message to all clients
        clients.emit("message", "Someone sent message #{data}")
    end

end

Subscribe an event in client side

var socket = new shivneriWsClient.Instance();
socket.on("message", function(data){
    console.log("data", data);
});

await socket.init(`<web-socket-url>`);

// emit event to server
socket.emit("message","Successfully connected")

Wanna deep dive ? Take a look at example real time chat