Created
April 24, 2010 15:53
-
-
Save pedromenezes/377733 to your computer and use it in GitHub Desktop.
WebSocket Chat with Node.JS and Sinatra
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 '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 |
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
// 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