启动 faye.ru rackup faye.ru -s thin -E production
本地测试挺好的, 但是部署到服务就完蛋了
WebSocket connection to 'ws://blind.codefordream.com:9292/faye' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
这是 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__)
require File.expand_path('../app/models/user_chat_list.rb', __FILE__)
require File.expand_path('../app/models/chat_message.rb', __FILE__)
require File.expand_path('../app/models/user_chat_online.rb', __FILE__)
environment = ENV['RACK_ENV'] || 'production'
dbconfig = YAML.load(File.read('config/database.yml'))
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'].match('/chat/*')
to_is_online= UserChatOnline.check_on_line(message['data']['to'], message['data']['from'], message['data']['content'], message['clientId'])
if !to_is_online
UserChatList.change_chat_list(message['data']['to'], message['data']['from'], "false")
ChatMessage.creat_new_chat_message(message['data']['from'], message['data']['to'], message['data']['content'])
end
end
if message['channel'] == '/meta/subscribe'
UserChatOnline.create_on_line_user(message['data']["from"], message['clientId'])
end
if message['channel'] == '/meta/disconnect'
UserChatOnline.remove_on_line_user(message['clientId'])
end
callback.call(message)
end
end
faye_server.on(:disconnect) do |client_id|
UserChatOnline.remove_on_line_user(client_id)
end
faye_server.add_extension(MarkOnline.new)
run faye_server
这是前台配置
var client = new Faye.Client('http://' + document.domain + ':9292' + '/faye');
client.subscribe('/chat/'+user_name, function (data) {
get_message_from_server(data.from, data.to, data.content);
show_from_message("from",data.content)
});
client.addExtension({
outgoing: function (message, callback) {
if (message.channel == '/meta/subscribe') {
message.data = {from: user_name};
}
if (message.channel == '/meta/disconnect') {
message.data = {from: user_name};
}
callback(message);
}
});
window.client = client;