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.
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>