Socket.io: geting multiple messages

Created on 9 Jul 2015  路  19Comments  路  Source: socketio/socket.io

Hi,

I am using socket.io for chating.
mycode:
app.js:

var express = require('express');
var app = express();
var http = require( "http" ).createServer( app );
var io = require( "socket.io" )( http );
var port = process.env.PORT || '8088';
http.listen(port);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use('/', routes);
app.use('/users', users);
app.use(function(req,res,next){
req.io = io;
next();
});
module.exports = app;

index.js:

var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', { title: 'Title' });
});
router.get('/chat', function(req, res) {
// usernames which are currently connected to the chat
var usernames = {};
var numUsers = 0;
var io=req.io;
io.on('connection', function (socket) {console.log("5");
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) {

    // 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;
    ++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 () {
    // remove the username from global usernames list
    if (addedUser) {
      delete usernames[socket.username];
      --numUsers;
      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });
});
res.render('chat', { title: 'Chat' });

});
module.exports = router;

chat.jade:

doctype html
html(lang="en")
head
meta(charset="UTF-8")
link(rel="stylesheet", href="/stylesheets/style.css")
body
ul.pages
li.chat.page
.chatArea
ul.messages
input.inputMessage(type="text", placeholder="Type here...")
li.login.page
.form
h3.title What"s your nickname?
input.usernameInput(type="text", maxlength="14")
script(src="https://code.jquery.com/jquery-1.10.2.min.js")
script(src="/javascripts/socket.io.js")
script(src="/javascripts/main.js")

When run the above script working fine, but getting multiple messages
Ex: if i refresh the page n times getting n messages

Help me.

Thanks
Pokal

Most helpful comment

use socket.removeAllListeners() at start up.

All 19 comments

use socket.removeAllListeners() at start up.

Thanks working..
I added in index.js after below line

io.on('connection', function (socket) {

is it correct place to add?

Yes.

ok thanks
How to implement 1-1 chat application?

Please help me....

What are your requirements for that?

just like gmail and facebook chat application.
I used express js , socket.io.
suggest me if any modules required for chat application.

You can use socket.io rooms for private chat; http://socket.io/docs/rooms-and-namespaces/

Just create a unique room ids for each private chat instance. And join both users to that room. And "emit"s will only be received by room members instead of a broadcast.

ok ..

how many chat rooms allowed to create?

Check this SO question; http://stackoverflow.com/questions/12246376/maximum-concurrently-open-rooms-in-socket-io

There is no limitation from socket.io side as fas as I know.

ok thanks i will try

HI,
I done 1-1 chat application.
is possible to get previous chat messages?

You should store them into some kind of DB and your app should retrieve them. It is not the duty of socket.io.

ok thanks

And gzip the css, js and doc. was not working

i tried gzip with different modules like:
compression,compress ...etc

Please close this question listed as 'issue'. For questions please use stackoverflow.
Code strong.

Hello pokal4u,

I like your concept to make facebook like chat app in socket.io.

I also want to build one for my intranet.
Can you please give demo code for that.

Thanks in advance

Seems it can be closed now. Feel free to reopen.

use socket.removeAllListeners() at start up.

this fixed my code, but I dont understand why.

use socket.removeAllListeners() at start up.

this fixed my code, but I dont understand why.

Here are my assumptions:
After you run your server, new users connect to it, but after closing a server, all connections it stays untouched, so I think that is why we need it.

I still have multiple messages of

"A new connection was made by a client."

Help me please anyone! Here is my code:

let config = require('./static/config'),
express = require('express'),
app = express(),
http = require('http').Server(app),
io = require('socket.io')(http);
....

http.listen(config.PORT, function () {
console.log('Server started at port', config.PORT);
});

http.on('connection', function(socket) {
socket.removeAllListeners();
console.log("A new connection was made by a client.");
socket.setTimeout(30 * 1000); // 30 second timeout. Change this as you see fit.
});

Was this page helpful?
0 / 5 - 0 ratings