Skip to content

Instantly share code, notes, and snippets.

@blaix
Created September 2, 2010 04:59
Show Gist options
  • Save blaix/561893 to your computer and use it in GitHub Desktop.
Save blaix/561893 to your computer and use it in GitHub Desktop.
Playing with websockets and EventMachine in the most cliche way possible.
<!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>
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
}
@thomasw
Copy link

thomasw commented Sep 2, 2010

Awesome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment