socket.io icon indicating copy to clipboard operation
socket.io copied to clipboard

geting multiple messages

Open pokal4u opened this issue 11 years ago • 20 comments

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

pokal4u avatar Jul 09 '15 05:07 pokal4u

use socket.removeAllListeners() at start up.

PritamUpadhyay avatar Jul 09 '15 06:07 PritamUpadhyay

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

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

is it correct place to add?

pokal4u avatar Jul 09 '15 06:07 pokal4u

Yes.

PritamUpadhyay avatar Jul 09 '15 06:07 PritamUpadhyay

ok thanks How to implement 1-1 chat application?

pokal4u avatar Jul 09 '15 06:07 pokal4u

Please help me....

pokal4u avatar Jul 09 '15 06:07 pokal4u

What are your requirements for that?

PritamUpadhyay avatar Jul 09 '15 06:07 PritamUpadhyay

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

pokal4u avatar Jul 09 '15 06:07 pokal4u

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.

cdagli avatar Jul 09 '15 07:07 cdagli

ok ..

how many chat rooms allowed to create?

pokal4u avatar Jul 09 '15 07:07 pokal4u

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.

cdagli avatar Jul 09 '15 07:07 cdagli

ok thanks i will try

pokal4u avatar Jul 09 '15 07:07 pokal4u

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

pokal4u avatar Jul 09 '15 09:07 pokal4u

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

cdagli avatar Jul 09 '15 10:07 cdagli

ok thanks

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

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

pokal4u avatar Jul 09 '15 10:07 pokal4u

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

dsalcedo avatar Aug 05 '15 02:08 dsalcedo

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

rahulp-evince avatar Dec 26 '15 08:12 rahulp-evince

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

nkzawa avatar Jan 17 '16 13:01 nkzawa

use socket.removeAllListeners() at start up.

this fixed my code, but I dont understand why.

Gib-git avatar Feb 22 '19 20:02 Gib-git

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. });

UtmostCreator avatar Oct 31 '19 15:10 UtmostCreator

use socket.removeAllListeners() at start up.

Thanks man!

BodyaNK avatar May 29 '21 12:05 BodyaNK