1

i am trying to include chat features on my MEAN app, all i have completed till now is a medium where all connected users can communicate.not a separate group. i follow some of the tutorials but they do by trick like sending some key words in front of message(whistle as they say). as far as i know every connected users are provided a seperate socket ID through which communication is carried but i failed getting that id.

module.exports = function(socket){   
  //console.log(socket);    
  var users =[];

  socket.on('username',function(data){
    users.push({id:socket.id,username:data.message});
    socket.emit('username',users)
  })
  console.log('connected');  
    socket.on('typing',function(data){
      //socket.emit('typing',{message:"helo angular"});
      socket.broadcast.emit('typing',{message:data.message});
  });

It shows me socket is not defined, any one has better idea how to perform private message using socket.io and node.js
can anyone enlighten me about this.

Mukesh Sharma
  • 8,914
  • 8
  • 38
  • 55
kisor
  • 464
  • 5
  • 22
  • where are you initialising `socket.io` server and creating new socket connection ? – Mukesh Sharma Jun 15 '16 at 09:13
  • @MukeshSharma on my main app.js my code goes here var server = require('http').Server(app); var io = require('socket.io')(server); var socket = require('./routes/socket.js'); server.listen(8000); console.log('server listening on port:8000'); io.on('connection',socket); – kisor Jun 15 '16 at 09:45
  • can you share error stack trace ? – Mukesh Sharma Jun 15 '16 at 10:45

1 Answers1

0

Make all users join their own unique group.

socket.join(socket.id);

Then you can send a message to one user by doing this

io.sockets.in(whichever_user.id).emit('msg', "Hello there user lets have a private chat!");


I would recommend using the Express framework of Node, and implenting Socket.io into it. Here are some links telling you how to set up Express and Socket.io:

https://www.youtube.com/watch?v=WH5qsGnFkBM&lc=z135dbryaqbfitiee22pd33ouozhwft3q

---Youtube comment tells you how to set up express generator.

Adrian Gąsiewicz:

For those who want to have similar directory structure as Bucky:

  1. Install Express generator "sudo npm install -g express-generator"

  2. Go to directory where you want to create project and type "express myapp --ejs" 3. Select newly created directory --> "cd myapp"

  3. Install all node_modules --> "npm install"

  4. Run server --> "npm start"

  5. Open browser and type "http://localhost:3000/" Have fun ;)

Using socket.io in Express 4 and express-generator's /bin/www

---This tells you how to set up socket in Node.js Express project.

Community
  • 1
  • 1
Melkor
  • 779
  • 1
  • 12
  • 29