以下是对Chase Gilliam 简洁回答的补充,其中包括对em-websocket、websocket-rails(很久没有维护)、faye-websocket-rails和ActionCable的引用。
我会推荐Plezi框架。它既可以用作独立的应用程序框架,也可以用作 Rails Websocket 增强功能。
我也会考虑以下几点:
您是否需要消息在连接之间持续存在(即,如果其他用户离线,消息是否应该在“消息框”中等待?消息应该等待多长时间?)...?
您希望保留消息历史记录吗?
这些要点将帮助您决定是否对消息使用持久存储(即数据库)。
即,要将Pleziinit_plezi.rb
与 Rails 一起使用,请在应用程序的config/initializers
文件夹中创建一个。使用(作为示例)以下代码:
class ChatDemo
# use JSON events instead of raw websockets
@auto_dispatch = true
protected #protected functions are hidden from regular Http requests
def auth msg
@user = User.auth_token(msg['token'])
return close unless @user
# creates a websocket "mailbox" that will remain open for 9 hours.
register_as @user.id, lifetime: 60*60*9, max_connections: 5
end
def chat msg, received = false
unless @user # require authentication first
close
return false
end
if received
# this is only true when we sent the message
# using the `broadcast` or `notify` methods
write msg # writes to the client websocket
end
msg['from'] = @user.id
msg['time'] = Plezi.time # an existing time object
unless msg['to'] && registered?(msg['to'])
# send an error message event
return {event: :err, data: 'No recipient or recipient invalid'}.to_json
end
# everything was good, let's send the message and inform
# this will invoke the `chat` event on the other websocket
# notice the `true` is setting the `received` flag.
notify msg['to'], :chat, msg, true
# returning a String will send it to the client
# when using the auto-dispatch feature
{event: 'message_sent', msg: msg}.to_json
end
end
# remember our route for websocket connections.
route '/ws_chat', ChatDemo
# a route to the Javascript client (optional)
route '/ws/client.js', :client
Plezi 设置了它自己的服务器(Iodine,一个 Ruby 服务器),所以请记住从您的应用程序中删除任何对puma
.thin
或任何其他自定义服务器的引用。
在客户端,您可能希望使用 Plezi 提供的 Javascript 助手(它是可选的)...添加:
<script src='/es/client.js' />
<script>
TOKEN = <%= @user.token %>;
c = new PleziClient(PleziClient.origin + "/ws_chat") // the client helper
c.log_events = true // debug
c.chat = function(event) {
// do what you need to print a received message to the screen
// `event` is the JSON data. i.e.: event.event == 'chat'
}
c.error = function(event) {
// do what you need to print a received message to the screen
alert(event.data);
}
c.message_sent = function(event) {
// invoked after the message was sent
}
// authenticate once connection is established
c.onopen = function(event) {
c.emit({event: 'auth', token: TOKEN});
}
// // to send a chat message:
// c.emit{event: 'chat', to: 8, data: "my chat message"}
</script>
我没有测试实际的消息代码,因为它只是一个骨架,而且它需要一个带有User
模型的 Rails 应用程序,并且token
我不想为了回答问题而编辑它(无意冒犯)。