Skip to content

Send message form outside EM block #6

@gathuku

Description

@gathuku

hey @imanel

I have been trying to send a message to the client from outside the EM block without success. I have the implementation in a Biometric module. I want from my controller to be able to set a message which will be sent to the client Biometric.set_message. When the message @@ms is not nil, send then message ws.send @@ms.

How can I be able to implement it?

require 'websocket-eventmachine-server'
require 'json'

module Biometric
  @@ms = nil

  def self.start
    EM.run do
      WebSocket::EventMachine::Server.start(host: '0.0.0.0', port: 7788) do |ws|
        ws.onopen do
          puts 'Client connected'
        end

        ws.onmessage do |msg, type|
          puts "Received message: #{msg} #{type}"
        end

        ws.onclose do
          puts 'client disconnected'
        end

        ws.send @@ms.to_json unless @@ms.nil?
       
      end
    end
  end

  def self.set_message(msg)
    @@ms = msg
  end
end

Biometric.start
Biometric.set_message('hello there')

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions