首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用于websocket-rails宝石的客户端

用于websocket-rails宝石的客户端
EN

Stack Overflow用户
提问于 2015-02-03 09:51:35
回答 1查看 2.7K关注 0票数 7

我正在开发一个rails网页,它需要使用websocket功能来与外部的ruby客户端进行通信。为了做到这一点,我在rails服务器中使用了websocket-rails gem,定义了client_connected client_disconnected事件和一个特定的操作来接收来自客户机(new_message)的消息。

在客户端,我尝试使用不同的红宝石,如faye-websocket-rubywebsocket-client-simple,但是当我试图发送消息时总是会出现错误。在服务器上,我找不到处理这些消息的方法。这两个宝石都有一个send方法,它只接受一个字符串(不能指定事件的名称)。

我一直使用的代码如下:

服务器端

app/controllers/chat_controller.rb

代码语言:javascript
复制
class ChatController < WebsocketRails::BaseController
  def new_message
    puts ')'*40
  end

  def client_connected
    puts '-'*40
  end

  def client_disconnected
    puts '&'*40
  end
end

config/events.rb

代码语言:javascript
复制
WebsocketRails::EventMap.describe do
  subscribe :client_connected, :to => ChatController, :with_method => :client_connected

  subscribe :message, :to => ChatController, :with_method => :new_message

  subscribe :client_disconnected, :to => ChatController, :with_method => :client_disconnected
end

config/initializers/websocket_rails.rb

代码语言:javascript
复制
WebsocketRails.setup do |config|
  config.log_path = "#{Rails.root}/log/websocket_rails.log"
  config.log_internal_events = true
  config.synchronize = false
end

客户端

websocket-client-simple

代码语言:javascript
复制
require 'rubygems'
require 'websocket-client-simple'

ws = WebSocket::Client::Simple.connect 'ws://localhost:3000/websocket'

ws.on :message do |msg|
  puts msg.data
end

ws.on :new_message do
  hash = { channel: 'example' }
  ws.send hash
end

ws.on :close do |e|
  p e
  exit 1
end

ws.on :error do |e|
  p e
end

hash = { channel: 'Example', message: 'Example' }
ws.send 'new_message', hash

loop do
  ws.send STDIN.gets.strip
end

faye-websocket

代码语言:javascript
复制
require 'faye/websocket'
require 'eventmachine'

EM.run {
  ws = Faye::WebSocket::Client.new('ws://localhost:3000/websocket')

  ws.on :open do |event|
    p [:open]
  end

  ws.on :message do |event|
    p [:message, event.data]
  end

  ws.on :close do |event|
    p [:close, event.code, event.reason]
    ws = nil
  end

  ws.send( 'Example Text' )
}

提前谢谢。致以问候。

如果你需要更多的代码,请告诉我。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-03 11:30:16

我终于找到了解决办法。问题是,为了让websocket理解消息,需要使用特定格式来构造消息。

示例:ws.send(“new_message”,{“data”:“示例消息”}‘)

其中new_message是websocket正在监听的事件。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28295874

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档