node.js - Socket.io connect event not firing -
this first time working node.js/socket.io , i'm having little trouble 'connect' event firing sockets. followed chat application example , tried add feature instead of displaying in console when user connects or disconnects, display on-screen.
the disconnect event firing tabs (if have multiple tabs open chat application), connect event seems fire current tab.
server (index.js)
var app = require('express')(); var http = require('http').server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendfile(__dirname + '/index.html'); }); io.on('connection', function(socket){ socket.on('connect', function(){ io.emit('connect', "a user connected"); }); socket.on('disconnect', function(){ io.emit('disconnect', "a user disconnected"); }); socket.on('chat message', function(msg){ io.emit('chat message', msg); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); });
client (index.html)
<script src="/socket.io/socket.io.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.js"></script> <script> var socket = io(); $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); socket.on('disconnect', function(msg){ $('#users').text(msg); }); socket.on('connect', function(msg){ $('#users').text(msg); }); </script>
you can try this, may work:
server:
var app = require('express')(); var http = require('http').server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendfile(__dirname + '/index.html'); }); io.on('connection', function(socket){ io.emit('new user', "a user connected"); socket.on('disconnect', function(){ io.emit('disconnect', "a user disconnected"); }); socket.on('chat message', function(msg){ io.emit('chat message', msg); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); });
client:
<script src="/socket.io/socket.io.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.js"></script> <script> var socket = io(); $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); socket.on('connect', function() { $('#users').text('i connected!'); }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); socket.on('disconnect', function(msg){ $('#users').text(msg); }); socket.on('new user', function(msg){ $('#users').text(msg); }); </script>
Comments
Post a Comment