Created
October 11, 2014 16:37
-
-
Save yukirii/b44cf9bf4de47c60ba8e to your computer and use it in GitHub Desktop.
WebSocket sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> | |
<script> | |
var ws = new WebSocket("ws://localhost:7070"); | |
ws.onopen = function() { | |
console.log("connected WebSocket server"); | |
} | |
ws.onclose = function() { | |
console.log("disconnected WebSocket server"); | |
} | |
ws.onmessage = function(e) { | |
var message_div = $('<div />').html(e.data); | |
$('div.data').prepend(message_div); | |
} | |
</script> | |
</head> | |
<body> | |
<h1>testapp</h1> | |
<div class="data"></div> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'em-websocket' | |
EM.run do | |
@channel = EM::Channel.new | |
puts "WebSocket Server start." | |
EM::WebSocket.start(host: '0.0.0.0', port: '7070') do |ws| | |
ws.onopen do | |
sid = @channel.subscribe {|message| ws.send(message) } | |
puts "<#{sid}> WebSocket connection open" | |
ws.onclose do | |
@channel.unsubscribe(sid) | |
puts "<#{sid}> disconnected" | |
end | |
end | |
end | |
EM::defer do | |
loop do | |
time = Time.now.to_s | |
@channel.push Time.now.to_s | |
puts "send data - #{time}" | |
sleep 1 | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment