NodeJS Cannot find module 'io' ( socket.io with express 4.15.3) - javascript
I am new in NodeJS. I am trying to run simple chat application with express and socket.io module, but when I run application, on the page where I am using socket, on console I am getting this error, and can't understand the problem. on web page I am getting this (see attached image)
Error: Cannot find module 'io'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at new View (/Applications/XAMPP/xamppfiles/htdocs/NODE/express/node_modules/express/lib/view.js:80:30)
Actually I have found this example in internet ( https://github.com/socketio/socket.io/tree/master/examples/chat ), and try to join it to my project.For view I am using EJS. All my JS and css files in public directory, I have copied socket.io.js from node_modules/socket.io-client/dist/socket.io.js to my javascript directory. Here is my code.
app.js
let express = require('express');
let bodyParser = require('body-parser');
let path = require('path');
let expressValidator = require('express-validator');
let db = require('mysql');
let sessions = require('express-session');
let session;
let app = express();
let connection = db.createConnection({
host:"localhost",
user:'root',
password:'',
database:'oulala'
});
connection.connect((error)=>{
if(error){
console.log('Error')
}else{
console.log("connected");
}
});
//Body parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(sessions({
secret:'$%2878asd8783yuh3b129x831726375r367*&^%$#',
resave:false,
saveUninitialized:true
}))
//View engine
app.set('view engine','ejs');
app.set('views',path.join(__dirname,'views'));
app.use(express.static(__dirname + '/public'));
//Global Vars
app.use((req,res,next)=>{
res.locals.errors = null;
res.locals.isAuthenticated = false;
next();
});
app.use(expressValidator({
errorFormatter: (param,msg,value)=>{
let namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length){
formParam+= '['+namespace.shift()+']';
}
return {
param : formParam,
msg : msg,
value : value
}
}
}));
app.get('/logout',(req,res)=>{
req.session.destroy((error)=>{
res.redirect('/');
})
})
app.post('/login',(req,res) => {
session = req.session;
req.checkBody('username','Username is required').notEmpty();
req.checkBody('password','Password is required').notEmpty();
errors = req.validationErrors();
if ( errors ) {
res.render('login',{
title:"Login",
errors:errors
});
}else{
if(req.body.username == 'admin' && req.body.password == 'admin'){
session.uniqueID = req.body.username;
isAuthenticated = true;
}
res.redirect('/');
}
})
app.get('/:page?',(req,res) => {
//res.send('Hello first page');
//res.json(people);
let page = req.params.page;
if ( page ) {
if ( page == 'posts' ){
connection.query("SELECT * FROM members",(error,rows,fields)=>{
if(error){
connection.release();
console.log('Error in the query - '+error);
}else{
res.render(page,{
title:page,
users:rows
});
}
});
}else{
res.render(page,{
title:page,
user:authenticate
});
}
}else{
session = req.session;
if(session.uniqueID){
res.render('index',{
title:"Index",
user:authenticate
});
}else{
res.render('login',{
title:"Login",
user:authenticate
});
}
}
});
// get form submition, post request
app.post('/users/add',(req,res) => {
//console.log(req.body.first_name); // req.body - request object
req.checkBody('first_name','Fisrtname is required').notEmpty();
req.checkBody('last_name','Lastname is required').notEmpty();
req.checkBody('email','Email is required').notEmpty();
errors = req.validationErrors();
if ( errors ) {
res.render('index',{
title:"Customers",
users:people,
errors:errors
});
}else{
var newUser = {
first_name:req.body.first_name,
last_name:req.body.last_name,
email:req.body.email
}
people.push(newUser);
res.render(page,{
title:page,
users:people,
user:authenticate
});
}
});
app.listen(3000, () => {
console.log('server started on port 3000....');
});
var server = require('http').createServer(app);
var io = require('socket.io')(server);
// Chatroom
var numUsers = 0;
io.on('connection', function (socket) {
var addedUser = false;
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'new message'
socket.broadcast.emit('new message', {
username: socket.username,
message: data
});
});
// when the client emits 'add user', this listens and executes
socket.on('add user', function (username) {
if (addedUser) return;
// we store the username in the socket session for this client
socket.username = username;
++numUsers;
addedUser = true;
socket.emit('login', {
numUsers: numUsers
});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username,
numUsers: numUsers
});
});
// when the client emits 'typing', we broadcast it to others
socket.on('typing', function () {
socket.broadcast.emit('typing', {
username: socket.username
});
});
// when the client emits 'stop typing', we broadcast it to others
socket.on('stop typing', function () {
socket.broadcast.emit('stop typing', {
username: socket.username
});
});
// when the user disconnects.. perform this
socket.on('disconnect', function () {
if (addedUser) {
--numUsers;
// echo globally that this client has left
socket.broadcast.emit('user left', {
username: socket.username,
numUsers: numUsers
});
}
});
});
client.js
$(function() {
var FADE_TIME = 150; // ms
var TYPING_TIMER_LENGTH = 400; // ms
var COLORS = [
'#e21400', '#91580f', '#f8a700', '#f78b00',
'#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
'#3b88eb', '#3824aa', '#a700ff', '#d300e7'
];
// Initialize variables
var $window = $(window);
var $usernameInput = $('.usernameInput'); // Input for username
var $messages = $('.messages'); // Messages area
var $inputMessage = $('.inputMessage'); // Input message input box
var $loginPage = $('.login.page'); // The login page
var $chatPage = $('.chat.page'); // The chatroom page
// Prompt for setting a username
var username;
var connected = false;
var typing = false;
var lastTypingTime;
var $currentInput = $usernameInput.focus();
var socket = io();
function addParticipantsMessage (data) {
var message = '';
if (data.numUsers === 1) {
message += "there's 1 participant";
} else {
message += "there are " + data.numUsers + " participants";
}
log(message);
}
// Sets the client's username
function setUsername () {
username = cleanInput($usernameInput.val().trim());
// If the username is valid
if (username) {
$loginPage.fadeOut();
$chatPage.show();
$loginPage.off('click');
$currentInput = $inputMessage.focus();
// Tell the server your username
socket.emit('add user', username);
}
}
// Sends a chat message
function sendMessage () {
var message = $inputMessage.val();
// Prevent markup from being injected into the message
message = cleanInput(message);
// if there is a non-empty message and a socket connection
if (message && connected) {
$inputMessage.val('');
addChatMessage({
username: username,
message: message
});
// tell server to execute 'new message' and send along one parameter
socket.emit('new message', message);
}
}
// Log a message
function log (message, options) {
var $el = $('<li>').addClass('log').text(message);
addMessageElement($el, options);
}
// Adds the visual chat message to the message list
function addChatMessage (data, options) {
// Don't fade the message in if there is an 'X was typing'
var $typingMessages = getTypingMessages(data);
options = options || {};
if ($typingMessages.length !== 0) {
options.fade = false;
$typingMessages.remove();
}
var $usernameDiv = $('<span class="username"/>')
.text(data.username)
.css('color', getUsernameColor(data.username));
var $messageBodyDiv = $('<span class="messageBody">')
.text(data.message);
var typingClass = data.typing ? 'typing' : '';
var $messageDiv = $('<li class="message"/>')
.data('username', data.username)
.addClass(typingClass)
.append($usernameDiv, $messageBodyDiv);
addMessageElement($messageDiv, options);
}
// Adds the visual chat typing message
function addChatTyping (data) {
data.typing = true;
data.message = 'is typing';
addChatMessage(data);
}
// Removes the visual chat typing message
function removeChatTyping (data) {
getTypingMessages(data).fadeOut(function () {
$(this).remove();
});
}
// Adds a message element to the messages and scrolls to the bottom
// el - The element to add as a message
// options.fade - If the element should fade-in (default = true)
// options.prepend - If the element should prepend
// all other messages (default = false)
function addMessageElement (el, options) {
var $el = $(el);
// Setup default options
if (!options) {
options = {};
}
if (typeof options.fade === 'undefined') {
options.fade = true;
}
if (typeof options.prepend === 'undefined') {
options.prepend = false;
}
// Apply options
if (options.fade) {
$el.hide().fadeIn(FADE_TIME);
}
if (options.prepend) {
$messages.prepend($el);
} else {
$messages.append($el);
}
$messages[0].scrollTop = $messages[0].scrollHeight;
}
// Prevents input from having injected markup
function cleanInput (input) {
return $('<div/>').text(input).text();
}
// Updates the typing event
function updateTyping () {
if (connected) {
if (!typing) {
typing = true;
socket.emit('typing');
}
lastTypingTime = (new Date()).getTime();
setTimeout(function () {
var typingTimer = (new Date()).getTime();
var timeDiff = typingTimer - lastTypingTime;
if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
socket.emit('stop typing');
typing = false;
}
}, TYPING_TIMER_LENGTH);
}
}
// Gets the 'X is typing' messages of a user
function getTypingMessages (data) {
return $('.typing.message').filter(function (i) {
return $(this).data('username') === data.username;
});
}
// Gets the color of a username through our hash function
function getUsernameColor (username) {
// Compute hash code
var hash = 7;
for (var i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + (hash << 5) - hash;
}
// Calculate color
var index = Math.abs(hash % COLORS.length);
return COLORS[index];
}
// Keyboard events
$window.keydown(function (event) {
// Auto-focus the current input when a key is typed
if (!(event.ctrlKey || event.metaKey || event.altKey)) {
$currentInput.focus();
}
// When the client hits ENTER on their keyboard
if (event.which === 13) {
if (username) {
sendMessage();
socket.emit('stop typing');
typing = false;
} else {
setUsername();
}
}
});
$inputMessage.on('input', function() {
updateTyping();
});
// Click events
// Focus input when clicking anywhere on login page
$loginPage.click(function () {
$currentInput.focus();
});
// Focus input when clicking on the message input's border
$inputMessage.click(function () {
$inputMessage.focus();
});
// Socket events
// Whenever the server emits 'login', log the login message
socket.on('login', function (data) {
connected = true;
// Display the welcome message
var message = "Welcome to Socket.IO Chat – ";
log(message, {
prepend: true
});
addParticipantsMessage(data);
});
// Whenever the server emits 'new message', update the chat body
socket.on('new message', function (data) {
addChatMessage(data);
});
// Whenever the server emits 'user joined', log it in the chat body
socket.on('user joined', function (data) {
log(data.username + ' joined');
addParticipantsMessage(data);
});
// Whenever the server emits 'user left', log it in the chat body
socket.on('user left', function (data) {
log(data.username + ' left');
addParticipantsMessage(data);
removeChatTyping(data);
});
// Whenever the server emits 'typing', show the typing message
socket.on('typing', function (data) {
addChatTyping(data);
});
// Whenever the server emits 'stop typing', kill the typing message
socket.on('stop typing', function (data) {
removeChatTyping(data);
});
socket.on('disconnect', function () {
log('you have been disconnected');
});
socket.on('reconnect', function () {
log('you have been reconnected');
if (username) {
socket.emit('add user', username);
}
});
socket.on('reconnect_error', function () {
log('attempt to reconnect has failed');
});
});
index.ejs
<% include partials/header %>
<h1><%= title %></h1>
<ul class="pages">
<li class="chat page">
<div class="chatArea">
<ul class="messages"></ul>
</div>
<input class="inputMessage" placeholder="Type here..."/>
</li>
<li class="login page">
<div class="form">
<h3 class="title">What's your nickname?</h3>
<input class="usernameInput" type="text" maxlength="14" />
</div>
</li>
</ul>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="/javascript/socket.io.js"></script>
<script src="/javascript/client.js"></script>
<% include partials/footer %>
package.json
{
"name": "customerapp",
"version": "1.0.0",
"description": "Simple customer managment app",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Anna Gabrielyan",
"license": "ISC",
"dependencies": {
"body-parser": "^1.17.2",
"ejs": "^2.5.6",
"express": "^4.15.3",
"express-session": "^1.15.3",
"express-validator": "^3.2.0",
"mysql": "^3.10.10",
"oauth2-server": "^2.4.1",
"socket.io": "^2.0.2"
}
}
First you need to install packages using below command
npm install
This command will install all the packages from your package.json once done you can run this program.
did you install socket.io using npm. if not try
npm install --save socket.io
can you show me package.json,?
I find my bug.
I removed this code
app.listen(3000, () => {
console.log('server started on port 3000....');
});
and added this
server.listen(3000);
after this
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
thanks to #Curious for helping and great answer
socket.io - can't get it to work, having 404's on some kind of polling call
Related
Node JS Imap-simple disconnect error after some time
I fetch unread messages in a middle ware that triggers my function every five minutes. It is successfully completing the request but eventually It triggers and crashes my nodejs process. With an error of: Error: This socket has been ended by the other party I have tried adding all these catches and error handling but It seams it eventually times out my connection to my inbox? Am I not reconnecting on every request to access my inbox? Here is my code (also I have tried with authTimeout: 3000 in the config before anyone suggests that is the issue): imap: { user: 'myemail#gmail.com', password: 'myPW', host: 'imap.gmail.com', port: 993, tls: true, keepalive: true } imaps.connect(settings.emailConfig).then(function (connection) { return connection.openBox('INBOX').then(function () { var searchCriteria = ['UNSEEN'];//only grab unread messages in LTS email var fetchOptions = { bodies: ['HEADER', 'TEXT', ''], markSeen: true//mark as read }; return connection.search(searchCriteria, fetchOptions).then(function (messages) { console.log('looking for unread messages') if (messages.length > 0) { console.log('unread messages to save') console.log('looking at messages : ' + util.inspect(messages, { depth: null })) var saveUnreadEmais = messages.map(function (item) {//resolve each promise of unread message var all = _.find(item.parts, { "which": "" }) var id = item.attributes.uid; var idHeader = "Imap-Id: " + id + "\r\n"; simpleParser(idHeader + all.body, (err, mail) => { var BarCode = ""; var subject = mail.subject; var to = mail.to.value[0].address; var from = mail.from.value[0].address; var text = mail.text; if (mail.subject.includes('Barcode :')) {//if the message to the system includes BarCode in the subject line grab it var split = mail.subject.split(':'); BarCode = split[1]; } if (!subject) { subject = "LTS Email Recieved - Barcode : " + BarCode; } if (!text) { text = "LTS auto email" } var newrec = {}; newrec.MessageDate = new Date(); newrec.MessageFor = to; newrec.MessageFrom = from; newrec.Message = text; newrec.MessageAbout = BarCode; newrec.MessageSubject = subject; newrec.MessageStatusCode = 1;//1 sent, 2 read, 3 saved, -1 deleted //console.log('saving message with details of : ' + util.inspect(newrec, { depth: null })) return db.knex('dbo.PersonnelMessages').insert(newrec).then((data) => { return "sent"; }); }); }); return Promise.all(saveUnreadEmais).then(() => { //do anything you want after saving all unred emails to our db. }).catch((err) => { console.log("error : " + err) }) } else { console.log('no new emails') } }).catch((err) => { console.log("error : " + err) }) }).catch((err) => { console.log("opening inbox error : " + err) }) }).then(function () { console.log('In the INBOX'); }).catch(function (e) { console.log('error : ' + e); });
How to get the socket id of a disconnected client on the disconnect event in socket.io
I have started working on a web application for othello.... in it I used node.js and socket.io for handling the server side code. It runs a server.js file in the cloud. This file handles some of the main client events, one of them is the disconnect event. Here's the code for disconnect event: io.sockets.on('connection', function(socket) { log('Client connection by '+socket.id); function log(){ var array = ['*** Server log Message']; for(var i=0; i< arguments.length; i++) { array.push(arguments[i]); console.log(arguments[i]); } socket.emit('log', array); socket.broadcast.emit('log', array); } /* disconnect command */ socket.on('disconnect', function(socket) { log(socket); log('Client disconnected '+ JSON.stringify(players[socket.id])); if('undefined' !== typeof players[socket.id] && players[socket.id]) { var username = players[socket.id].username; var room = players[socket.id].room; var payload = { username: username, socket_id: socket.id }; delete players[socket.id]; io.in(room).emit('player_disconnected', payload); } }); }); This disconnect command should notify all the other cleints about the disconnected player and delete the data about it. Here's the code for holding the temporary data of the active players: /* join_room command */ socket.on('join_room', function(payload) { log('\'join_room\' command '+ JSON.stringify(payload)); if(('undefined' === typeof payload) || !payload) { var error_message = 'join_room had no payload, command aborted'; log(error_message); socket.emit('join_room_response', { result: 'fail', message: error_message }); return; } var room = payload.room; if(('undefined' === typeof room) || !room) { var error_message = 'join_room didn\'t specify a room, command aborted'; log(error_message); socket.emit('join_room_response', { result: 'fail', message: error_message }); return; } var username = payload.username; if(('undefined' === typeof username) || !username) { var error_message = 'join_room didn\'t specify a username, command aborted'; log(error_message); socket.emit('join_room_response', { result: 'fail', message: error_message }); return; } /* store information about new player */ players[socket.id] = {}; players[socket.id].username = username; players[socket.id].room = room; log(players); socket.join(room); var roomObject = io.sockets.adapter.rooms[room]; /* notify others about new player */ var sumCleints = roomObject.length; var data = { result: 'success', room: room, username: username, socket_id: socket.id, membership: sumCleints }; io.in(room).emit('join_room_response', data); for(var socket_in_room in roomObject.sockets) { var data = { result: 'success', room: room, username: players[socket_in_room].username, socket_id: socket_in_room, membership: sumCleints }; socket.emit('join_room_response', data); } log('join_room success'); log('Room: '+ room + ' was just joined by '+ username) }); But the issue is it doesn't. When I logged the socket.id, it returns undefined, I don't know why ... when I log the socket itself, it says: transport closed. My question is how to get the socket id of a player who just disconnected. Here's the client side code for handling the player_disconnected event: /* when someone leaves a room */ socket.on('player_disconnected', function(payload) { if (payload.result == 'fail') { alert(payload.message); return; } if(payload.socket_id == socket_id) { return; } /* Delete all rows for new players that leave */ var dom_elements = $('.socket_'+payload.socket_id); if(dom_elements.length != 0) { dom_elements.slideUp(1000); } var newHTML = '<p>'+payload.username+' has left the lobby</p>'; var newNode = $(newHTML); newNode.hide(); $('#messages').append(newNode); newNode.slideDown(1000); }); If someone could figure out the problem than please tell me, and please tell me how the disconnect event, and the other events actually work and what are the parameters for them, because I couldn't find any useful information in the docs... Thanks in advance.
On disconnect, you are overriding the socket variable with a different callback parameter. Try this: /* disconnect command */ socket.on('disconnect', function() { console.log(socket.id); });
jquery.js: Uncaught ReferenceError: connect is not defined
I run this code on a website with a database, this interacts with the ambiance.js , jquery.js (3.2.1) and socket.js but I believe this requires some other dependency that I omitted. var SOCKET = null; var user = null; $(document).ready(function() { connect(); }); function request(msg) { var m=msg; if(m.type == 'aMessage') { console.log(m.msg); } function connect() { if(!SOCKET) { var hash = getCookie('hash'); if (hash == '') { $.ambiance({message: 'Please login!'}); } else { $.ambiance({message: 'Connecting to server..', type: 'success'}); } SOCKET = io(':4095'); SOCKET.on('connect', function(msg) { if(hash != '') { $.ambiance({message: 'Connected', type: 'success'}); } SOCKET.emit('hash', { hash: hash }); }); SOCKET.on('connect_error', function(msg){ $.ambiance({message: 'Connection lost', type: 'error'}); }); SOCKET.on('request', function(msg){ request(msg); }); } } }
Actually, you created the connect() function inside the request function (which wasn't called yet): Just move it outside and it should work.
Accounts.sendVerificationEmail Issue in Meteor
I Need to send VerificationEmail using Meteor.I did the code but It didn't send VerificationEmail and also got error on server side.Error is : Can't find user.I didn't have any idea about this.so Please see the below code & suggest me how to do. JS Code: if (Meteor.isClient) { Template.main.events ({ 'submit #register-form' : function (e,t) { console.log("You pressed the button Register "); e.preventDefault(); var username = t.find('#username').value , name = t.find('#name').value , email = t.find('#email1').value , password = t.find('#pwd1').value; console.log("password="+password); var isValidPassword = function(val, field) { if (val.length >= 6) { return true; } else { Session.set('displayMessage', 'Error & Too short.') return false; } } if (isValidPassword(password)) { console.log(" *** isValidPassword *** "); Accounts.createUser({email: email, password : password,username : username }, function(err) { if (err) { console.log(err); } else { console.log("Register Successfully"); Meteor.call('sendEmail', '*****#gmail.com', '****.com', 'Hello from Meteor!', 'This is a test of Email.send.'); } }); } else { console.log("*** Error ***"); } } }); } if (Meteor.isServer) { Meteor.startup(function () { // code to run on server at startup }); //Meteor methods Meteor.methods ({ sendEmail: function (to, from, subject, text) { Accounts.config({sendVerificationEmail: true, forbidClientAccountCreation: false}); process.env.MAIL_URL = 'smtp://****#gmail.com:*pwd*#smtp.gmail.com:587'; this.unblock(); Accounts.sendVerificationEmail(to); } }); }
Did you send the email to an email address? When you use to in Accounts.sendVerificationEmail(to); it must be the _id of the user you want to send the confirmation email to, not their email address.
Socket.io disconnect event triggering on new connection
I am trying to build a chat server and client using node and socket.io following a tutorial from a book.The front-end code is as follows: <html> <head> <title>Socket.IO example application</title> <style type = "text/css"> #input { width: 200px; } #messages { position: fixed; top: 40px; bottom: 8px; left: 8px; right: 8px; border: 1px solid #EEEEEE; padding: 8px; } </style> </head> <body> Your message: <input id = "input" type = "text" /> <div id = "messages"></div> <script src = "http://localhost:4001/socket.io/socket.io.js"></script> <script type = "text/javascript"> var messagesElement = document.getElementById('messages'); var lastMessageElement = null; function addMessage (message) { var newMessageElement = document.createElement('div'); var newMessageText = document.createTextNode(message); newMessageElement.appendChild(newMessageText); messagesElement.insertBefore(newMessageElement, lastMessageElement); lastMessageElement = newMessageElement; } var socket = io.connect('http://localhost:4001'); socket.on('login', function() { var username = prompt('What username would you like to use?'); socket.emit('login', username); }); socket.on('serverMessage', function (content) { addMessage(content); }); function sendCommand(command, args) { if(command === 'j') { socket.emit('join', args); } else { alert('unknown command: ' + command); } } function sendMessage(message) { var commandMatch = message.match(/^\/(\w*)(.*)/); if(commandMatch) { sendCommand(commandMatch[1], commandMatch[2].trim()); } else { socket.emit('clientMessage', message); } } var inputElement = document.getElementById('input'); inputElement.onkeydown = function(keyboardEvent) { if(keyboardEvent.keyCode === 13) { sendMessage(inputElement.value); inputElement.value = ''; return false; } else { return true; } }; </script> </body> </html> And back-end is: /*jslint node: true */ var httpd = require('http').createServer(handler); var io = require('socket.io').listen(httpd); var fs = require('fs'); function handler(req, res) { "use strict"; fs.readFile(__dirname + '/index.html', function (err, data) { if (err) { res.writeHead(500); return res.end('Error Loading index.html'); } res.writeHead(200); res.end(data); }); } httpd.listen(4001); io.sockets.on('connection', function (socket) { "use strict"; socket.on('login', function(username) { socket.set('username', username, function (err) { if (err) { throw err; } socket.emit('serverMessage', 'Currently logged in as ' + username); socket.broadcast.emit('serverMessage', 'User ' + username + ' logged in'); }); }); socket.on('clientMessage', function (content) { socket.emit('serverMessage', 'You said: ' + content); socket.get('username', function (err, username) { if (!username) { username = socket.id; } socket.get('room', function (err, room) { if (err) { throw err; } var broadcast = socket.broadcast, message = content; if (room) { broadcast.to(room); } broadcast.emit('serverMessage', username + ' said: ' + message); }); }); }); socket.on('join', function (room) { socket.get('room', function (err, oldRoom) { if (err) { throw err; } socket.set('room', room, function (err) { if (err) { throw err; } socket.join(room); if (oldRoom) { socket.leave(oldRoom); } socket.get('username', function (err, username) { if (!username) { username = socket.id; } socket.emit('serverMessage', 'You joined room' + room); }); socket.get('username', function (err, username) { if (!username) { username = socket.id; } socket.broadcast.to(room).emit('serverMessage', 'User ' + username + ' joined this room'); }); }); }); }); socket.on('disconnect', function() { socket.get('username', function (err, username) { if (!username) { username = socket.id; } socket.broadcast.emit('serverMessage', 'User ' + username + ' disconnected'); }); }); socket.emit('login'); }); The problem I am facing is that whenever a new user logs in, all the previous users get a message saying "User " + randomID + "disconnected" before the new user logs in and it functions normally. This problem does not occur if a new user logs in quickly after the immediately previous user logged in (I'm guessing it has something to do with heartbeat here). I'd really appreciate any help in figuring out why this disconnect event is being triggered every time a new user logs in. Thanks.
alert or prompt in javascript are blocking functions, they stop all javascript events on browsers. That is why the 'heart' inside socket.io stops beating. In more detail: In every heartbeat, the server sends a packet to the clients for checking if the clients are alive or dead, and if a client is not responsive, the server thinks it is dead. The solution is replacing prompt function with async function, a popup div, form, etc...
i have been copy your code,and run in my server,i can't find your problem what your are facing,but i find a problem, when i cancel the usename input window,my user name is null, i find my userid is random string. when i disconnect, socket.io will boardcast a message like that, "User " + randomID + "disconnected"