var express = require('express'),
server = express.createServer(),
io = require('socket.io');
server.configure(function(){
server.use(express.logger());
server.use(express.staticProvider(__dirname + '/www/public'));
});
server.listen(3000);
// socket.io
var socket = io.listen(server),
buffer = [];
socket.on('connection', function(client){
client.send({buffer: buffer});
client.broadcast({announcement: client.sessionId + ' connected'});
// new client is here!
client.on('message', function(message){
client.send({ message: "got your message: " + message});
client.broadcast({ message: client.sessionId + " sent message: " + message});
});
client.on('disconnect', function(){
client.broadcast({announcement: client.sessionId + ' disconnected'});
});
});
2. www/public/index.html
<html>
<head>
<title> Test </title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<h1> Hello NodeJS </h1>
<p> This is a static folder </p>
<p id="ann">empty now</p>
<p id="chat">empty now</p>
<script>
var socket = new io.Socket(null, {port: 3000});
socket.connect();
socket.on("message", function(obj) {
console.dir(obj);
if('buffer' in obj) {
document.getElementById('chat').innerHTML = '';
}
else {
if('announcement' in obj)
document.getElementById('ann').innerHTML = obj.announcement;
else
document.getElementById('chat').innerHTML = obj.message;
}
});
socket.send("this is the test message");
</script>
</body>
</html>
No comments:
Post a Comment