I´m making a simple real time application.
I have a page with a square and when I click the square is painted or remove the paint.
I want make the event in one tab and see his effect in other tab.
I dont have too much experience with node.js and socket.io
There is my server:
var sock = require('socket.io')
, express = require('express')
, path = require('path')
var app = express();
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/', function (req,res) {
io.sockets.in(req.sessionID);
res.render(__dirname + '/views/teste.jade');
});
io = sock.listen(app.listen(3000));
io.sockets.on('connection', function(socket){
var sess = socket.handshake.session;
socket.on('hasClass', function(data) {
socket.emit('hasClass', {hasClass: data.hasClass})
});
});
And there is my .jade:
doctype 5
html
head
title= "Express"
link(rel='stylesheet', href='/stylesheets/style.css')
script(src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js")
script(src="/socket.io/socket.io.js")
script
$(document).ready(function() {
var socket = io.connect('http://localhost:3000');
socket.on('connect', function(){
$('#quadrado').click(function() {
if ($('#quadrado').hasClass('clicked')) {
socket.emit('hasClass', {hasClass:true});
} else {
socket.emit('hasClass', {hasClass:false});
}
});
});
socket.on('hasClass', function(data){
if(data.hasClass) {
$('#quadrado').removeClass('clicked');
} else {
$('#quadrado').addClass('clicked');
}
});
});
body
block content
In your server code, the following:
socket.on('hasClass', function(data) {
socket.emit('hasClass', {hasClass: data.hasClass})
});
will simply re-emit the event to the socket you got the event from. If you want to send it to every other socket, use:
socket.broadcast.emit(...);
and if you want to send it to every socket, including the one that received it, use
io.sockets.emit(...);