WebSockets+Redis构建EventMachine
WebSockets+Redis构建EventMachineEventMachine 是一个Ruby的事件驱动网络库,本文不是要介绍它,而是要介绍一个以Redis 的 Pub/Sub 机制为后端,以WebSockets为前端的类EventMachine实现。
前端代码,创建Socket连接到本地8081端口,当有消息push过来的时候,将消息打印到指定的div里:<!DOCTYPE html>
<html>
<head>
<title>Websockets!</title>
<script>
function onMessage(evt) {
con = document.getElementById("console");
con.innerHTML += evt.data;
con.innerHTML += '<br />';
}
websocket = new WebSocket("ws://localhost:8081");
websocket.onmessage = function(evt) { onMessage(evt); };
</script>
</head>
<body>
<div id="console">
</div>
</body>
</html>后端代码:
require 'redis'
require 'em-websocket'
SOCKETS = []
@redis = Redis.new(:host => '127.0.0.1', :post => 6379)
# Creating a thread for the EM event loop
Thread.new do
EventMachine.run do
# Creates a websocket listener
EventMachine::WebSocket.start(:host => '0.0.0.0', :port => 8081) do |ws|
ws.onopen do
# When someone connects I want to add that socket to the SOCKETS array that
# I instantiated above
puts 'creating socket'
SOCKETS << ws
end
ws.onclose do
# Upon the close of the connection I remove it from my list of running sockets
puts 'closing socket'
SOCKETS.delete ws
end
end
end
end
# Creating a thread for the redis subscribe block
Thread.new do
@redis.subscribe('ws') do |on|
# When a message is published to 'ws'
on.message do |chan, msg|
puts "sending message: #{msg}"
# Send out the message on each open socket
SOCKETS.each {|s| s.send msg}
end
end
endsleep开启8081端口接受连接,同时连到Redis上订阅ws这个key的消息
当前后端都启动并连接上后,你就可以用如下代码往Redis的ws这个key上写消息,页面上就能看到push过来的消息了:require 'redis'
@redis = Redis.new(:host => '127.0.0.1', :post => 6379)
@redis.publish 'ws', 'Something witty'来源:jessedearing.com
have fun!
谢谢分享
页:
[1]