在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進行實時通信了。