28. Server
require 'em-websocket'
trap(:INT){EM.stop}
EM.run do
connections = []
EM::WebSocket.run(:host => "0.0.0.0", :port => 28080) do |ws|
ws.onopen do |handshake|
puts "New connection"
connections << ws
end
ws.onclose do
connections.delete(ws)
end
ws.onmessage do |msg|
puts "Message coming: #{msg}"
connections.each{|conn| conn.send(msg) }
end
end
end
連線池
76. fork model
• for Unix Like OS only
• 由⽗父⾏行程fork出⼦子⾏行程
• ⼦子⾏行程有和⽗父⾏行程⼀一樣的記憶體內容
• ⾏行程間的記憶體不互通
• ⾏行程間共享fork前已開啟的IO
• 由Copy on Write⽅方式節省未變更記憶體
使⽤用(Ruby 2.0+ feature)
85. r2p = Redis.new #Publisher⽤用連線
EventMachine.run do
emredis = EM::Hiredis.connect# Subscriber⽤用
pids = 2.times do |pi|
pid = fork do#############FORK START#####################
EventMachine::WebSocket.start(.....) do |ws|
ws.onopen do |request|
...
ws.onmessage do |ws_msg|
#1. Client傳訊給worker
msg = current_room.messages.create(...)
#2. 向master channel通知有新訊息
r2p.publish 'master', msg.id.to_s
end
emredis.pubsub.subscribe('child') do |mid|/
msg = Message.find(mid)
EM.next_tick do#4. worker們得到master傳來的新訊息,傳給⾃自⼰己的clients
$connections[current_room.db_name.to_sym].each do |s|
s.send(render_messages([msg]))
end
end
end
end
end
end#############FORK END#####################
end
emredis.pubsub.subscribe('master') do |msg|
r2p.publish('child', msg)#3. MASTER得到訊息,通知workers
end
end