Skip to content

Instantly share code, notes, and snippets.

@pedromenezes
Created April 24, 2010 15:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save pedromenezes/377733 to your computer and use it in GitHub Desktop.
Save pedromenezes/377733 to your computer and use it in GitHub Desktop.
WebSocket Chat with Node.JS and Sinatra
require 'rubygems'
require 'sinatra'
get '/' do
'
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<form>
<label for="message">mensagem:</label>
<input type="text" id="message" name="message">
<input type="submit" value="enviar">
</form>
<div id="messages"></div>
<script>
var chat = new WebSocket("ws://189.106.97.39:8080");
chat.onopen = function(){
chatPrint("Você entrou no chat");
}
chat.onmessage = function(data){
chatPrint(data.data);
}
function chatPrint(message){
document.getElementById("messages").innerHTML = "<p>" + message + "</p>" + document.getElementById("messages").innerHTML;
}
document.getElementsByTagName("form")[0].onsubmit = function(){
chat.send(document.getElementById("message").value);
document.getElementById("message").value= "";
return false;
}
</script>
</body>
</html>'
end
// using http://github.com/tristandunn/node-websocket
var sys = require('sys'),
WebSocket = require('./node-websocket/lib/websocket').WebSocket,
Connection = require('./node-websocket/lib/connection').Connection;
var people = [],
Chat = Connection;
Chat.prototype.onopen = function() {
sys.puts('New connection.');
people.push(this);
};
Chat.prototype.onmessage = function(data) {
for (var x = 0; x < people.length; x++){
people[x].send(data);
}
};
Chat.prototype.onclose = function() {
sys.puts('Lost connection.');
};
new WebSocket(Chat);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment