Rails websocket

Rails中怎么使用WebSocket进行实时通信

小亿
92
2024-06-03 14:39:12
栏目: 编程语言

在Rails中使用WebSocket进行实时通信需要先安装并配置Action Cable。Action Cable是Rails中提供的用于处理WebSocket连接的框架。

首先安装Action Cable:

rails generate channel Chat

然后在config/routes.rb中配置路由:

mount ActionCable.server => '/cable'

接着在app/channels/chat_channel.rb中编写WebSocket处理逻辑:

class ChatChannel < ApplicationCable::Channel
  def subscribed
    stream_from "chat_channel"
  end

  def receive(data)
    ActionCable.server.broadcast("chat_channel", data)
  end
end

在前端使用JavaScript连接WebSocket并进行实时通信:

App.chat = App.cable.subscriptions.create("ChatChannel", {
  connected: function() {
    console.log("Connected to chat channel");
  },
  disconnected: function() {
    console.log("Disconnected from chat channel");
  },
  received: function(data) {
    console.log("Received message: ", data);
  },
  send: function(message) {
    this.perform('receive', { message: message });
  }
});

App.chat.send("Hello, world!");

最后在视图中使用Action Cable的辅助方法进行连接:

<%= action_cable_meta_tag %>

通过以上步骤,就可以在Rails中使用WebSocket进行实时通信了。

0
看了该问题的人还看了