Created
September 2, 2010 04:59
-
-
Save blaix/561893 to your computer and use it in GitHub Desktop.
Playing with websockets and EventMachine in the most cliche way possible.
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'> | |
<title>omgsockets</title> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> | |
<script> | |
$(document).ready(function() { | |
var ws = new WebSocket('ws://localhost:3000'); | |
ws.onmessage = function(msg) { | |
$('#chat').append("<p>" + msg.data + "</p>"); | |
} | |
$('input#submit').click(function() { | |
ws.send($('input#message').val()); | |
return false; | |
}) | |
}) | |
</script> | |
</head> | |
<body> | |
<h1>Cyberchats</h1> | |
<div id="chat"> | |
</div> | |
<form> | |
<input type="text" id="message"> | |
<input type="submit" id="submit" value="send"> | |
</form> | |
</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
require 'em-websocket' | |
EventMachine::run { | |
@sockets = [] | |
EventMachine::WebSocket.start(:host => 'localhost', :port => 3000) do |ws| | |
ws.onopen do | |
puts "Connection opened." | |
@sockets << ws | |
end | |
ws.onclose do | |
puts "Connection closed." | |
@sockets.delete(ws) | |
end | |
ws.onmessage do |msg| | |
puts "Received message: #{msg}" | |
@sockets.each { |socket| socket.send(msg) } | |
end | |
end | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome.