connect and quit message on main channel - node.js

I want to send message to users if some new person is joining or user is quiting the chat.
i don't really know where to start to get this function work.
On disconnect message 'This users is gone' to all On Connect "user is connected to the chatbox"
app.js
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
nicknames = [];
server.listen(8000);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
socket.on('new user', function(data, callback){
if (nicknames.indexOf(data) != -1){
callback(false);
} else{
callback(true);
socket.nickname = data;
nicknames.push(socket.nickname);
updateNicknames();
}
});
function updateNicknames(){
io.sockets.emit('usernames', nicknames);
}
socket.on('send message', function(data){
io.sockets.emit('new message', {msg: data, nick: socket.nickname});
});
socket.on('disconnect', function(data){
if(!socket.nickname) return;
nicknames.splice(nicknames.indexOf(socket.nickname), 1);
updateNicknames();
});
})
;

You can use the broadcast function. This will broadcast to every other socket except the one that send the broadcast.
socket.on('disconnect', function () {
socket.broadcast.emit('leave',{name:name});
});
socket.on('leave', function (msg) {
//Add msg that msg.name is leaving
});

Related

Why is io.sockets.in not working with my code?

Client Side script
var socket = io.connect();
var room = "abc123";
socket.on('connect', function() {
socket.emit('room', room);
});
socket.on('message', function(data) {
console.log('Incoming message:', data);
});
Server side script
io = socketio.listen(server);
io.sockets.on('connection', function(socket) {
socket.on('room', function(room) {
socket.join(room);
});
});
room = "abc123";
io.sockets.in(room).emit('message', 'what is going on, party
people?');
I am trying to send message to abc123 but io.sockets is not working.

Insert data in mongodb using Socket.io

i am developing simple chat application and i want to store messages in mongoDb.
but i am getting error when i run this code.
can not read property '_id 'of undefined. i already create one collection call chat.
var MongoClient= require('mongodb').MongoClient;
var assert=require('assert');
var ObjectId= require('mongodb').ObjectId;
var bodyParser= require('body-parser');
var express = require('express'),
app=express();
server=require('http').createServer(app),
io= require('socket.io').listen(server),
app.use(bodyParser.urlencoded({extended:false}));
var mongo=require('mongodb');
users = {};
url='mongodb://localhost:27017/anant';
server.listen(9000, function(){
var host= server.address().address;
var port=server.address().port;
console.log("save app listen on http://%s:%s", host , port);
});
/*var server = app.listen(9000, function(){
var host= server.address().address;
var port=server.address().port;
console.log("save app listen on http://%s:%s", host , port);
});*/
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
socket.on('new user', function(data , callback){
if(data in users){
callback(false);
}else{
callback(true);
socket.nickname= data;
users[socket.nickname]= socket;
updatenicknames();
}
});
io.sockets.on('send request', function(data , callback){
var name=data;
console.log(data);
});
socket.on('send message', function(data , callback){
var msg=data.trim();
if(msg.substr(0,3) === '/w '){
msg = msg.substr(3);
var ind = msg.indexOf(' ');
console.log(ind);
console.log("got it after ind ");
if(ind !== -1)
{
var name=msg.substr(0, ind);
var msg=msg.substring(ind + 1);
console.log(name);
console.log(msg);
if(name in users){
console.log("got it in if name condition");
users[name].emit('wishper', {msg: msg , nick: socket.nickname} );
console.log('whisper..! ');
} else
{
callback("enter a vlid user");
}
} else{
callback('please enter message for your wishper');
}
}else {
insertData(data);
io.sockets.emit('new message', {msg: msg , nick: socket.nickname} );
}
});
function updatenicknames(){
io.sockets.emit('usernames', Object.keys(users));
}
function insertData(data)
{
MongoClient.connect(url, function(err, db){
console.log(data);
db.collection('chat').save(data.msg , (err,result)=>{
if(err){
console.log("not inserted");
}else {
console.log("inserted");
}
});
});
}
socket.on('disconnect', function(data){
if(!socket.nickname) return;
delete users[socket.nickname];
updatenicknames();
});
});
It's because you are passing a string data, to your insertData function (judging by your code, I guess you are supposing that data is actually an object).
Then you are giving data.msg, which is obviously undefined, as the first argument of the save methods, which is expecting you to provide a valid object here.
Please also note that you are using the save method on a newly created document, instead of using insertOne.
As you can see in the api documentation, using save is now deprecated. (I guess you are using the last version which is currently 2.1)

Issue with socket.io join room

I have a issue with socket.io with rooms.
See the server code:
This code below is working properly.
io.on('connection', function(socket){
socket.join("myroom");
socket.on('chat message', function(data){
io.in("myroom").emit('chat message', data);
});
});
But I want the user to enter the room after an event.
Like the code below.
io.on('connection', function(socket){
socket.on('chat message', function(data){
io.in("myroom").emit('chat message', data);
});
socket.on('join', function(name, device, room){
socket.join("myroom");
});
});
It's almost the same code , but does not work. What am I doing wrong?
The event is being called correctly.
Edit. Added the front-end code:
var socket = io.connect('http://localhost:5000');
$('#msg_form').submit(function(){
socket.emit('chat message', $("#m").val(), "myroom");
$('#m').val('');
return false;
});
$("#user").submit(function() {
var name = $("#name").val();
var room = $("#room").val();
var device = navigator.userAgent;
if (name === "" || name.length < 2) {
$("#errors").empty();
$("#errors").append("Please enter a name");
$("#errors").show();
} else {
socket.emit("join", name, device, room);
$("#messages").focus();
}
});
Thank you.
I made this small demo to explain, I simulate the client-side event by setTimeout functions:
Server side:
var http = require('http');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(9999);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.on('message', function(data){
io.in("myroom").emit('message', data);
});
socket.on('join', function(name, device, room){
console.log("new client has joining a room");
socket.join("myroom");
});
});
Client Side:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:9999');
setTimeout(function () { console.log("msg emmited to server");
socket.emit('join');
},
10000);
setTimeout(function () {
console.log("msg emmited to server");
socket.emit("message","message from client");
},
20000);
socket.on("message",function(data){
console.log("message received from server ="+data);
}
);
</script>
In your $("#user").submit(...) handler, you do not prevent the default action of the form so it is likely that the page is reloaded right after you hit the submit button. And, this will reset your connection right after you hit join, giving you a newly initialize connection that is not joined into the room.
You can either add return false; to that handler or add the e argument to the handler and call e.preventDefault() to prevent the page from reloading when you hit submit.
$("#user").submit(function(e) {
e.preventDefault();
var name = $("#name").val();
var room = $("#room").val();
var device = navigator.userAgent;
if (name === "" || name.length < 2) {
$("#errors").empty();
$("#errors").append("Please enter a name");
$("#errors").show();
} else {
socket.emit("join", name);
$("#messages").focus();
}
});

socket.io emitting message to room does not work

Events binding for socket are moved to separate module:
exports.bind = function(socket) {
socket.on('join', function(data) {
socket.join(data.type);
});
socket.on('message', function(data) {
global.io.sockets.in('rooma').emit('message', data);
});
}
server.js:
var app = express();
//creating socket server
server = http.createServer(app);
io = global.io = require('socket.io').listen(server, {'log level': 3});
io.sockets.on('connection', function(socket) {
//binding events on socket
events.bind(socket, io);
});
The problem is, that message is never sent to the clients in 'rooma'. But if i emit it global:
global.io.sockets.emit('message', data);
It works. Where can be problem? I've tested the client belongs to room for sure.
this works when you get the initialisation of the event from the room to which you like to send your message:
exports.bind = function(socket) {
socket.on('join', function(data) {
socket.join(data.type);
});
socket.on('message', function(data) {
socket.get('room', function (error, room) {
io.sockets.in(room).emit('message', data);
});
});
}

WebSockets with node.js

I'm trying an example of WebSocket to develop a simple chat.
server.js:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8080);
function handler (req, res) {
fs.readFile(__dirname + '/test.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
and test.html:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('connect', function() {
alert('<li>Connected to the server.</li>');
});
socket.on('message', function(message) {
alert(message);
});
socket.on('disconnect', function() {
alert('<li>Disconnected from the server.</li>');
});
function sendF(){
var message = "Test";
socket.send(message);
alert('Test Send');
}
In test.html I have also a simple button that onClick call sendF.
If I try it I see on my browser an alert when I CONNECT, SEND, and DISCONNCT, and if I check in console, I see the message.
But I cannot receive the same message in response from server, to show it in my browser! I think socket.on('message'... is not working for me!
Your server.js is missing event listeners. It's also missing where you are doing the send of the message to be displayed in the browser.
io.sockets.on('connection', function (socket) {
console.log('user connected');
socket.send('hello world');
socket.on('disconnect', function () {
console.log('user disconnected.');
});
socket.on('message', function (data) {
console.log(data);
});
});

Resources