我正在写一个简单的实时聊天,所以我决定使用网络套接字。我用了gem 'faye-rails'
。 Web控制台显示它正常POST http://khersonchat.herokuapp.com/faye [HTTP/1.1 200 OK 170ms]
,但当我发送消息时出现错误:While loading the page connection ws://khersonchat.herokuapp.com/faye was broken
(从俄语翻译)。因此,当我发送消息时,整个页面仍然会重新加载,我需要重新加载页面以查看其他人发送的消息。
messages_controller.rb
:
def create
respond_to do |format|
if current_user
@message = current_user.messages.build(message_params)
if @message.save
flash[:success] = 'Message sent'
else
flash[:error] = 'Oops, an error :('
end
format.html {redirect_to root_path}
format.js
else
format.html {redirect_to root_path}
format.js {render nothing: true}
end
end
end
application.js
:
//= require jquery
//= require jquery_ujs
//= require faye
//= require messages
//= require_self
//= require turbolinks
messages.coffee
:
window.client = new Faye.Client('/faye')
jQuery ->
$('#new_message').submit ->
$(this).find("input[type='submit']").val('Sending...').prop('disabled', true)
try
client.unsubscribe('/messages')
catch
console?.log "Can't unsubscribe"
client.subscribe '/messages', (payload) ->
$('#messages').find('.media-list').append(payload.message) if payload.message
create.js.erb
publisher = client.publish('/messages', {
message: '<%= j render @message %>'
});
publisher.callback(function() {
$("#message_body").val('');
$("#new_message").find("input[type='submit']").val('Send').prop('disabled', false)
});
publisher.errback(function() {
alert('Oops, an error');
});
https://github.com/AlexNikolaev94/chatclone.git - 最新源代码
重要!聊天通过omniauth
使用社交网络 Vkontakte(vk.com)进行身份验证,因此存储在git中的版本可以访问本地主机