Ok, here is a really simple example. A textarea synchronizes with login members.
Please install http, socket.io and express(ver3).
sudo npm install http, socket.io, express
And create a javascript file.
server.js
var app = require('express')(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
member_sockets = {},
key;
server.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
var user_id = socket.id;
member_sockets[user_id] = socket;
console.log("[login]-->", user_id);
socket.on('txt_change', function (data) {
for (key in member_sockets) {
if (key != user_id) {
member_sockets[key].emit("txt_change", data);
}
};
});
socket.on('disconnect', function (socket) {
console.log("[logout]-->", user_id);
delete member_sockets[user_id];
});
});
In the same directory, you also create an index.html file.
index.html
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('txt_change', function (data) {
console.log(data);
$("#txt").val(data.txt);
});
$(document).ready(function(){
$("#txt").keyup(function(){
socket.emit('txt_change', { "txt" : $(this).val() });
});
});
</script>
</head>
<body>
<textarea id="txt" style="width:200px;height:100px"></textarea>
</body>
</html>
Then run the server with this command:
sudo node server.js
So the code should work like this picture: