0

I am trying to create a chat application using node js and mongodb. I am looking on a tutorial for this. I couldn't solve a error that states socket is not defined while running my file server.js. The code in server Js is

var mongo = require('mongodb').MongoClient,
client = require('socket.io').listen(8080).sockets;
console.log(mongo);
mongo.connect('mongodb://@127.0.0.1/chat',function(err,db) {
    if(err) throw err;  
    client.on('connection',function() {     
        //Wait for Input
        socket.on('input',function(data) {
        console.log(data);
    });
});

});

The error is created when i wanted to listen socket on input.When i try to define socket as socket =io.connect('http://127.0.0.1:8080'); It again gives error stating io not defined. Isn't io global on nodejs?

Please enlighten me on this.

7
  • Are You using express ? Commented Sep 8, 2014 at 9:28
  • Please provide more detailed code of server.js Commented Sep 8, 2014 at 9:29
  • I don't see where you define your io variable Commented Sep 8, 2014 at 9:29
  • I am not using express. I am following a tutorial where express is not mentioned Commented Sep 8, 2014 at 10:50
  • @Loupax how should i define my io. ISnt io a global variable ??? Commented Sep 9, 2014 at 9:28

1 Answer 1

1

Try as below if you are using express.

var express  = require('express'),
, app        = express()
, server     = require('http').Server(app)
, mongo      = require('mongodb').MongoClient,
, io         = require('socket.io')(server);

server.listen(3000, function() {
     console.log("Server Running on port 3000");
});   


mongo.connect('mongodb://@127.0.0.1/chat',function(err,db) {

      io.sockets.once('connection', function(socket) {

       io.sockets.emit('new-data', {
        channel: 'stdout',
        value: "My Data"
     });

   });

});

In you view.html

   <html>

   <head>
     <script src="https://cdn.socket.io/socket.io-1.0.6.js"></script>

     var socket = io.connect('http://localhost');
     var streamer = $('#streamer');

     socket.on('new-data', function(data) {
        streamer.val(data.value);
     });
  </head>

  <body>
      <div id="streamer"> </div>
  </body>

  </html>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.