前段时间项目要实现群聊系统,项目是ruby on rails写的,后来就选择了faye,faye是一个实时推送的服务器,如果不知道faye,建议去官网了解下,http://faye.jcoglan.com/ 折腾了挺长时间,记录一下遇到的坑,以防以后在碰到了,或者能给需要的人看。碰到最大的坑就是要标记在线用户的信息。
首先在Gemfile 中添加
gem 'faye-rails'
gem 'thin' //我用的是通过thin来跑的服务器
并且在applation.js中添加
//=require faye
我一开始是通过在applation.rb中进行配置让faye 和rails一起启动,本地跑的没有问题,但通过nginx部署到服务器的时候会开启不了服务,后来我把faye server独立出来,在工程目录下新建faye.ru文件,文件噢诶之如下
require 'faye'
require File.expand_path('../config/initializers/faye_token.rb', __FILE__)
require 'active_record'
require 'mysql2'
require 'yaml'
Faye::WebSocket.load_adapter('thin')
RAILS_ENV = ENV['RACK_ENV']
require File.expand_path('../app/models/user_chat_room.rb', __FILE__)
environment = ENV['RACK_ENV'] || 'production'
dbconfig = YAML.load(File.read('config/database.yml')) //添加database
ActiveRecord::Base.establish_connection(dbconfig[environment])
faye_server = Faye::RackAdapter.new(:mount => '/faye', :timeout => 60) //
class MarkOnline
def incoming(message, callback)
faye_client ||= Faye::Client.new('http://localhost:9292/faye')
if message['channel'] == '/meta/subscribe'
if message['data'] != nil
UserChatRoom.mark_on_line( message['data']['user'], //登陆上线
message['data']['id'],
message['data']['sex'],
message['clientId']
)
online_user = UserChatRoom.current_online
faye_client.publish('/message', online_user) //把上线人的信息push给所有人
end
elsif message['channel'] == '/meta/disconnect'
UserChatRoom.mark_off_line(message['clientId'])
online_user = UserChatRoom.current_online //下线
faye_client.publish('/message', online_user)
end
callback.call(message)
end
end
faye_server.on(:disconnect) do |client_id| //每60秒监测一次,如果连接已断,把这个人的信息删除下线
UserChatRoom.mark_off_line(client_id)
faye_client ||= Faye::Client.new('http://localhost:9292/faye')
online_user = UserChatRoom.current_online
faye_client.publish('/message', online_user)
end
faye_server.add_extension(MarkOnline.new)
run faye_server
applation.html.erb中添加
<%= javascript_include_tag 'application',"http://#{request.host}:9292/faye.js" 'data-turbolinks-track' => true %>
前台js
client = new Faye.Client('http://' + document.domain + ':9292' + '/faye'); // new 监听事件
client.subscribe('/chat', function (payload) { //接收server传来的消息 } client.publish('/chat', { //向server push消息 });
后来又为聊天添加了表情,以及图片,原理都一样,图片是通过二进制流来传输,表情就是类似chat表情一样,参考的文章是nodejs
http://www.cnblogs.com/wayou/p/hichat_built_with_nodejs_socket.html