express setImmediate(function () { error - node.js

Im busy with a chat app with nodejs 6 socketio 1.7.2 express 4.14.1.
i can run node index.js but as soon as i access my page simplechat.html
it throws the below error. Please help
/root/Chat/node_modules/express/lib/response.js:1013
setImmediate(function () {
^ ReferenceError: setImmediate is not defined
at Array.onfinish [as 0] (/root/Chat/node_modules/express/lib/response.js:1013:5)
at listener (/root/Chat/node_modules/express/node_modules/on-finished/index.js:169:15)
at onFinish (/root/Chat/node_modules/express/node_modules/on-finished/index.js:100:5)
at callback (/root/Chat/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js:55:10)
at ServerResponse.onevent (/root/Chat/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js:93:5)
at ServerResponse.EventEmitter.emit (events.js:126:20)
at ServerResponse.OutgoingMessage._finish (http.js:837:8)
at ServerResponse.OutgoingMessage.end (http.js:822:10)
at onend (stream.js:66:10)
at EventEmitter.emit (events.js:126:20)
Package json file
{
"name": "Chat",
"version": "0.0.0",
"description": "ERROR: No README.md file found!",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": "",
"author": "",
"license": "BSD",
"dependencies": {
"express": "~4.14.1",
"socket.io": "~1.7.2"
}
Index.js File
// We need to use the express framework: have a real web server that knows how to send mime types etc.
var express=require('express');
// Init globals variables for each module required
var app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
// Indicate where static files are located
//app.configure(function () {
app.use(express.static(__dirname + '/'));
//});
// launch the http server on given port
server.listen(8000,'***.***.**.**');
console.log('Server running at http://***.***.***.**:8000/');
// routing
app.get('/', function (req, res) {
res.sendFile(__dirname + '/simpleChat.html');
});
// usernames which are currently connected to the chat
var usernames = {};
io.sockets.on('connection', function (socket) {
// when the client emits 'sendchat', this listens and executes
socket.on('sendchat', function (data) {
// we tell the client to execute 'updatechat' with 2 parameters
io.sockets.emit('updatechat', socket.username, data);
});
// when the client emits 'adduser', this listens and executes
socket.on('adduser', function(username){
// we store the username in the socket session for this client
socket.username = username;
// add the client's username to the global list
usernames[username] = username;
// echo to client they've connected
socket.emit('updatechat', 'SERVER', 'you have connected');
// echo globally (all clients) that a person has connected
socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
// update the list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
});
// when the user disconnects.. perform this
socket.on('disconnect', function(){
// remove the username from global usernames list
delete usernames[socket.username];
// update list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
// echo globally that this client has left
socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
});
});
SimpleChat.html
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var socket = io.connect(); // we might pass the URL of the WS server as parameter here
// on connection to server, ask for user's name with an anonymous callback
socket.on('connect', function(){
// call the server-side function 'adduser' and send one parameter (value of prompt)
socket.emit('adduser', prompt("What's your name?"));
});
// listener, whenever the server emits 'updatechat', this updates the chat body
socket.on('updatechat', function (username, data) {
$('#conversation').append('<b>'+username + ':</b> ' + data);
});
// listener, whenever the server emits 'updateusers', this updates the username list
socket.on('updateusers', function(data) {
$('#users').empty();
$.each(data, function(key, value) {
$('#users').append('<div>' + key + '</div>');
});
});
// on load of page
$(function(){
// when the client clicks SEND
$('#datasend').click( function() {
var message = $('#data').val();
$('#data').val('');
// tell server to execute 'sendchat' and send along one parameter
socket.emit('sendchat', message);
});
// when the client hits ENTER on their keyboard
$('#data').keypress(function(e) {
if(e.which == 13) {
$(this).blur();
$('#datasend').focus().click();
}
});
});
</script>
<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
<b>USERS</b>
<div id="users"></div>
</div>
<div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
<div id="conversation"></div>
<input id="data" style="width:200px;">
<input type="button" id="datasend" value="send">
</div>

Related

node.js refusing connection?

I have some node.js code that I am running called app.js When it runs is gives an error saying connection refused?
It is running on plesk so I cannot debug it. I have added the package.json too but maybe I am missing something?
package.json:
{
"name": "socket-example",
"version": "0.0.1",
"description": "test socket.io app",
"dependencies": {
"socket.io": "^1.7.3"
},
"scripts": {
"start": "node app.js"
}
}
app.js:
var http = require('http');
var fs = require('fs');
// Loading the index file . html displayed to the client
var server = http.createServer(function(req, res) {
fs.readFile('./index.html', 'utf-8', function(error, content) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
// Loading socket.io
var io = require('socket.io').listen(server);
// When a client connects, we note it in the console
io.sockets.on('connection', function (socket) {
console.log('A client is connected!');
});
server.listen(8080);
index.html:
<body>
<h1>Communicating with socket.io!</h1>
<p><input type="button" value="Poke the server" id="poke" /></p>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
// The visitor is asked for their username...
var username = prompt('What\'s your username?');
// It's sent with the signal "little_newbie" (to differentiate it from "message")
socket.emit('little_newbie', username);
// A dialog box is displayed when the server sends us a "message"
socket.on('message', function(message) {
alert('The server has a message for you: ' + message);
})
// When the button is clicked, a "message" is sent to the server
$('#poke').click(function () {
socket.emit('message', 'Hi server, how are you?');
})
</script>
</body>
Try changing all you code like this as this will resolve your issues
app.js
var express = require('express');
var app = express();
app.set("view engine","html");
var http = require('http');
//making express server for routes
var server = http.Server(app);
// Loading socket.io
var io = require('socket.io')(server);
//index route
//loaded when the website is loaded root route.
app.get('/',function(req,res){
//specify the path to the directory (assuming both are in the same directory)
res.sendFile(__dirname + '/index.html');
})
// When a client connects, we note it in the console
io.sockets.on('connection', function (socket) {
console.log('A client is connected!');
//message of client side
socket.on('little_newbie',function(message){
//give the username in terminal of the connected client
console.log(message);
//send a hello to the client from the server.
io.sockets.emit('message',"Hello "+message);
})
//button poke mesage response
socket.on('message',function(message){
//print the hello message from the server
console.log(message)
//after this you can send a response back to the client as in the above case
io.sockets.emit('poke',"Hi I am fine ");
})
});
server.listen(8080);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Socket.io</title>
</head>
<body>
<h1>Communicating with socket.io!</h1>
<p><input type="button" value="Poke the server" id="poke" /></p>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('/');
// The visitor is asked for their username...
var username = prompt('What\'s your username?');
// It's sent with the signal "little_newbie" (to differentiate it from "message")
socket.emit('little_newbie', username);
// A dialog box is displayed when the server sends us a "message"
socket.on('message', function(message) {
alert('The server has a message for you: ' + message);
})
// When the button is clicked, a "message" is sent to the server
$('#poke').click(function () {
socket.emit('message', 'Hi server, how are you?');
})
socket.on('poke',function(message){
alert(message);
})
</script>
</body>
{
"name": "socket-example",
"version": "0.0.1",
"description": "test socket.io app",
"dependencies": {
"express": "^4.16.4",
"socket.io": "^1.7.3"
},
"scripts": {
"start": "node app.js"
}
}
There ate no routes configuration , and when you try to ping from browser it won't connect . just like meaning less URI. Try making a route and then calking route from Browser.

Running a socket.io server in a real live server, instead of localhost?

I found a coding from tutorials point to run a a simple socket.io chat server in localhost, I installed necessary environments like nodejs, express, init package.json and I started the server from terminal using command-"node app.js", then I accessed the index page in my localhost it showed the chat page, it is working fine. But the thing is I want to use this is in a live server for my office, to chat within the office. Is this code is enough for that. I am new to this socket.io and nodejs. My office has live server for hosting their website, this code opens and listens to port 3000. It will be highly helpful if you could tell me how to run this in a real server.
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
</head>
<script src = "/socket.io/socket.io.js"></script>
<script>
var socket = io();
function setUsername() {
socket.emit('setUsername', document.getElementById('name').value);
};
var user;
socket.on('userExists', function(data) {
document.getElementById('error-container').innerHTML = data;
});
socket.on('userSet', function(data) {
user = data.username;
document.body.innerHTML = '<input type = "text" id = "message">\
<button type = "button" name = "button" onclick = "sendMessage()">Send</button>\
<div id = "message-container"></div>';
});
function sendMessage() {
var msg = document.getElementById('message').value;
if(msg) {
socket.emit('msg', {message: msg, user: user});
}
}
socket.on('newmsg', function(data) {
if(user) {
document.getElementById('message-container').innerHTML += '<div><b>' +
data.user + '</b>: ' + data.message + '</div>'
}
})
</script>
<body>
<div id = "error-container"></div>
<input id = "name" type = "text" name = "name" value = ""
placeholder = "Enter your name!">
<button type = "button" name = "button" onclick = "setUsername()">
Let me chat!
</button>
</body>
</html>
app.js Server
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res) {
res.sendfile('index.html');
});
users = [];
io.on('connection', function(socket) {
console.log('A user connected');
socket.on('setUsername', function(data) {
console.log(data);
if(users.indexOf(data) > -1) {
socket.emit('userExists', data + ' username is taken! Try some
} else {
users.push(data);
socket.emit('userSet', {username: data});
}
});
socket.on('msg', function(data) {
//Send message to everyone
io.sockets.emit('newmsg', data);
})
});
http.listen(3000, function() {
console.log('listening on localhost:3000');
});
You can solve your problem through nginix( A reverse proxy server). Nginx have .conf file which contains the server realted configuration.
server { listen 3000; server_name io.yourhost.com; }
To run:
Sudo service nginx start
It will start your server on given IP or Domain name.
Change the declaration variable socket by
var socket = io(Server IP + ':port');
Example:
var socket = io('127.0.0.1:3000);
I using socket.io version 2.0.2

How to clear redis database when nodejs server disconnect?

I have a simple chatroom application using a node express server.
This uses a redis database connection to store the nicknames of the joined clients.
I need to clear the redis SET of nicknames named members when the server is closed/disconnected.
This can be done as following:
redisClient.del("members", function(err, reply){
console.log("members set delete :" + reply);
});
But where should I put this code? How to handle the final event from the server when disconnection, from the server side?
Server code - chatroom.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var redis = require('redis');
var redisClient = redis.createClient();
io.on('connection', function(client){
console.log("client connected...");
});
io.on('connection', function(client){
client.on('join', function(name){
client.nickname = name;
//adding names
client.broadcast.emit("add member", name);
redisClient.smembers('members', function(err, names) {
names.forEach(function(name){
client.emit('add member', name);
});
});
client.emit('add member', client.nickname)
redisClient.sadd("members", name);
});
// remove clients on disconnect
client.on('disconnect', function(name){
client.broadcast.emit("remove member", client.nickname);
redisClient.srem("members", client.nickname);
});
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/views/index.html');
});
server.listen(8080);
Client code - views/index.html
<html>
<head>
<title>Socket.io Client</title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<h2>Chat box</h2><br>
<h4 id="status"></h4><br>
<div>
<h3>Active members</h3>
<ul id="members"></ul>
</div>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('connect', function(data){
nickname = prompt("What is your nickname?");
$('#status').html('Connected to Chat Room as \''+nickname+'\'.');
socket.emit('join', nickname);
});
socket.on('add member', function(name) {
var member = $('<li>'+name+'</li>').data('name', name);
$('#members').append(member);
});
socket.on('remove member', function(name) {
$('#members li').filter(function() { return $.text([this]) === name; }).remove();
});
socket.on('disconnect', function(data){
$('#status').html('Chatroom Server Down!');
});
</script>
</body>
</html>
How to clear the redis database set when nodejs server disconnect?
you can use error or end events on redisclient, check the Redis Package Documentation
redisClient.on("error", function (err) {
console.log("Error " + err)
// delete here
});
However, since your connection is closed, it is more healthy to delete on first connection to redis each time. do it on reconnection state too.
When a socket.io connection dies, an event named disconnect is fired. Register your reset logic to that callback.
io.sockets.on('connection', function (socket) {
socket.on('disconnect', function () {
redisClient.del("members", function(err, reply){
console.log("members set delete :" + reply);
});
});
});
Credits : How can i handle Close event in Socket.io?

JS change socket namespace from client when click on button

I'm developping simple app with nodejs and socket.io.
I created two channels and I want my client connect one of channels when click on button. The problem is I don't get response from server
This is my code :
// SERVER side
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var nameSpaceWeek = io.of('/week');
var nameSpaceDay = io.of('/day');
app.get('/', function(req, res){
res.sendfile('MDC.html');
});
io.on('connection', function(socket){
console.log("User = " + socket.id)
});
nameSpaceDay.on('connection', function(socket){
console.log('someone connected on namespace day');
nameSpaceDay.emit('hiDay', 'Hello everyone on namespace day!');
});
nameSpaceWeek.on('connection', function(socket){
console.log('someone connected on namespace week');
nameSpaceDay.emit('hiWeek', 'Hello everyone on namespace week!');
});
http.listen(3000, function(){
console.log('listening on localhost:3000');
});
// CLIENT SIDE
<!DOCTYPE html>
<html>
<head><title>Hello world</title></head>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
function setDay(){
console.log("setDay");
socket = io.connect('/day');
console.log(socket)
}
socket.on('hiDay',function(data){
console.log("hiDay")
console.log("data = ." + data + ".")
document.getElementById('message-container').innerHTML = 'Update day'
console.log("data = ." + data + ".")
});
function setWeek(){
console.log("setWeek");
socket = io.connect('/week');
console.log(socket)
}
socket.on('hiWeek',function(data){
console.log("hiWeek")
document.getElementById('message-container').innerHTML = 'Update Week'
//document.getElementById('message-container').innerHTML = data
console.log(data)
});
</script>
<body>
<div id="message-container"></div>
<div id="error-container"></div>
<button type="button" name="button" onclick="setWeek()">Week</button>
<button type="button" name="button" onclick="setDay()">Day</button>
</body>
In my client, I created two button and when I click on one I want change socket namespace
When you call setDay() or setWeek(), you are creating a whole new socket.io connection and thus overwriting your previous socket variable. The socket.on(hiDay, ...) and socket.on('hiWeek', ...) handlers you have are ONLY on the first socket you created, not on the newly created sockets, thus you never see the messages on those.
To fix, add those message handlers only to the right socket after you've connected to that namespace.
function setWeek() {
// close previous socket.io connection
socket.close();
// make new connection to new namespace
console.log("setWeek");
socket = io.connect('/week');
console.log(socket)
// add event handler for new socket
socket.on('hiWeek',function(data){
console.log("hiWeek")
document.getElementById('message-container').innerHTML = 'Update Week'
console.log(data)
});
}
Then, do the same thing for the setDay() function.
And, as shown here you probably want to disconnect the previous connection when changing namespaces too so you don't necessarily leave connections that you aren't using any more.
FYI, you also had a typo where this:
nameSpaceDay.emit('hiWeek', 'Hello everyone on namespace week!');
should have been this:
nameSpaceWeek.emit('hiWeek', 'Hello everyone on namespace week!');
Final, tested and working code is this:
<!DOCTYPE html>
<html>
<head><title>Hello world</title></head>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
function setDay(){
socket.close();
console.log("setDay");
socket = io.connect('/day');
socket.on('hiDay',function(data){
console.log("hiDay")
document.getElementById('message-container').innerHTML = 'Update day';
console.log(data);
});
}
function setWeek() {
// close previous socket.io connection
socket.close();
// make new connection to new namespace
console.log("setWeek");
socket = io.connect('/week');
// add event handler for new socket
socket.on('hiWeek',function(data){
console.log("hiWeek");
document.getElementById('message-container').innerHTML = 'Update Week';
console.log(data);
});
}
</script>
<body>
<div id="message-container"></div>
<div id="error-container"></div>
<button type="button" name="button" onclick="setWeek()">Week</button>
<button type="button" name="button" onclick="setDay()">Day</button>
</body>
And server code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');
var nameSpaceWeek = io.of('/week');
var nameSpaceDay = io.of('/day');
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'socket-io-namespace.html'));
});
io.on('connection', function(socket){
console.log("User = " + socket.id)
});
nameSpaceDay.on('connection', function(socket){
console.log('someone connected on namespace day');
nameSpaceDay.emit('hiDay', 'Hello everyone on namespace day!');
});
nameSpaceWeek.on('connection', function(socket){
console.log('someone connected on namespace week');
nameSpaceWeek.emit('hiWeek', 'Hello everyone on namespace week!');
});
http.listen(3000, function(){
console.log('listening on localhost:3000');
});
If you create a connect(ns) function you can reconstruct the socket event listener when the namespace changes. The following should work:
<script>
var connect = function (ns) {
return io.connect(ns, {
query: 'ns=' + ns,
resource: "socket.io"
}).on('hiWeek', function (data) {
console.log("hiWeek")
document.getElementById('message-container').innerHTML = 'Update Week'
//document.getElementById('message-container').innerHTML = data
console.log(data)
}).on('hiDay', function (data) {
console.log("hiDay")
console.log("data = ." + data + ".")
document.getElementById('message-container').innerHTML = 'Update day'
console.log("data = ." + data + ".")
});
}
var socket = io();
function setDay() {
console.log("setDay");
socket = connect('/day');
console.log(socket);
}
function setWeek() {
console.log("setWeek");
socket = connect('/week');
console.log(socket);
}
</script>

private chat with socket.io

I'm having trouble with my chat app, I need to be able to send a private message to a specific user, I was able to select that specific user but for some reason couldn't figure out how to send the private message.
Below you will find the code for my server, please help:
var express = require('express');
var app = express();
var PORT = process.env.PORT || 8000;
var http = require('http').Server(app); // this is a node server that uses express as the boiler plate
var io = require('socket.io')(http); // socket! pass our server as a parameter to it
// use express static to expose a folder
app.use(express.static(__dirname + '/public'));
var users = [],
connections = [];
var onlineClients = {};
// Register events on socket connection
io.on('connection', function(socket){
connections.push(socket);
// console.log("connected socket", connections);
socket.on("disconnect", function() {
users.splice(users.indexOf(socket.username), 1);
updateUsernames();
connections.splice(connections.indexOf(socket), 1);
console.log("disconnected socket", connections.length)
});
socket.on("send message", function(data) {
// console.log(data);
io.emit("new message", {msg: data, user: socket.username});
});
socket.on("notify user", function(data) {
io.emit("notify user", {user: socket.username})
});
socket.on("new user", function(data) {
socket.username = data;
users.push(socket.username);
updateUsernames();
});
function updateUsernames() {
io.emit("get users", users);
};
socket.on("private", function(data, recipientName) {
var recipient = connections.filter(function (recipient) {
return recipient.username === recipientName;
})[0];
console.log(recipient.id);
console.log(data);
io.sockets.socket(recipient.id).emit("received private msg", data);
});
// socket.on("create room", function(room) {
// socket.join(room);
// io.sockets.in(room).emit('event', "hey wusup am in this room");
// console.log(socket);
// })
});
http.listen(PORT, function(){
console.log('Server started on port ' + PORT);
});
First add user in chat room so that will easy to find a user in your private chat room
Your client side code for join private room
<input type="text" class="form-control" id="user_email" placeholder="user_email" />
<button text="join room" class="btn btn-primary btn-block" onclick="a();"> Join Room</button>
your javascript code in client side
function a(){
io.emit('privatechatroom', {email:document.getElementById('user_email').value});
}
your server side code to add user in your room
socket.on('privatechatroom',function(data){
socket.join(data.email);
io.emit('res',{mes:"you are added"})
});
now u can send private message to that person that is recently addedd to this room
client side
function b() {
io.emit('sendmail', { email: document.getElementById('sender_mail').value, message: document.getElementById('message').value });
$('#message').val('');
}
/*serverside code*/
socket.on('sendmail', function (data) {
io.sockets.in(data.email).emit('new_msg', { msg: data.message });
console.log(data.email);
});
Here is the clear solution of mine for your question...
Send a message to Particular client(Private chat)
I hope it will work for you sue..

Resources