Node.js on cloud 9 connection problems - javascript

I'm using Node.js in cloud 9, and I can't seem to figure out how to connect the client to socket.io. I've searched everywhere but I can't seem to find out what my problem is.
The node.js server file:
var express = require('express');
var http = require('http');
var io = require('socket.io');
var app = express();
var path = require("path");
var users;
app.get('/', function(req, res){
res.sendfile('index.html', {root: __dirname});
});
var server = app.listen(process.env.PORT, process.env.IP);
console.log("Server listening on: "+process.env.PORT+" "+ process.env.IP);
server.on('connection', function(socket){
socket.emit('welcome', {message : 'Welcome', id : socket.id});
socket.on('client', function(data){
console.log("Client response"+data);
});
socket.on('username', function(data){
console.log('Username recieved: '+data['username']);
});
});
The client-side javascript code:
<script>
var socket = io.connect("https://march-madness-rentarosatomi5201.c9.io");
socket.on('welcome', function(data){
alert(data.message+" "+data.id);
socket.emit('client', {data: 'hello', id: data.id});
});
function send(){
username = document.getElementById('username_box').value;
alert(username);
socket.emit('username', {username: username});
}
</script>

On the client-side you need something like:
<script src="https://march-madness-rentarosatomi5201.c9.io/socket.io/socket.io.js"></script>
<script>
var socket = io.connect("https://march-madness-rentarosatomi5201.c9.io");
....

Related

Triggering socket.io real-time notifications from Express 4 middleware

I am building a real-time notification system using socket.io. This is my server-side code at the moment:
bin/www:
var app = require('../app');
var server = http.createServer(app);
var io = app.io
io.attach(server);
server.listen(port, function(err) {
if (err) console.log(err);
console.log('Listening on port ' + port + '...');
});
app.js:
var socket_io = require('socket.io');
var express = require('express');
var app = express();
var io = socket_io();
app.io = io;
require('./config/socket')(app.io);
config/socket.js:
var User = require('../controllers/user');
module.exports = function (io) {
io.on('connection', function (socket) {
console.log('Socket.io connected');
socket.emit('connection', "Connection created.");
socket.on('send notification', function(data) {
User.createNotification(socket.request.user, data);
});
});
};
routes/index.js:
var express = require('express');
var User = require('../controllers/user');
var router = express.Router();
router.post('/order', User.order);
module.exports = router;
controllers/user.js:
var User = require('../models/user').model;
var io = require('socket.io');
module.exports = {
order: function(req, res) {
/* some create order code */
io.emit('send notification', 'Your order was successful!');
res.sendStatus(200);
}
}
I keep getting the error TypeError: io.emit is not a function whenever I try to call the route POST /send even though I am clearly initiating socket.io in my app.js and bin/www files and requiring it in controllers/user.js. All the examples I've seen online emit notifications from within this part:
io.on('connection', function (socket) {
socket.emit(event, msg);
});
but I want my notifications to be triggered from the middleware so I can send custom notifications to the user when certain events happen in the application backend.
Try the following instead:
io.on('connection', function(socket){
socket.on('xxx', function(obj){
io.emit('xxx', {xxx: xxx})
})
})
This should suppress your TypeError:.

Initialize Socket.IO from server instance in another module

I want to initialize my socket inside a route and according to documents I have to pass server instance to my socket. I have a separate server.js file like this:
var app = require('./app');
var http = require('http');
var port = '2002';
app.set('port', port);
var server = http.createServer(app);
server.listen(port, function(err){
if(err)
console.log(err);
else
console.log('Server listening on port : ' + port);
});
module.exports = server;
and my router:
var express = require('express');
var server = require('../server');
var router = express.Router();
var io = require('socket.io')(server);
router.get('/', function(req, res, next){
res.render('index');
});
router.post('/', function(req, res, next){
io.on('connection', function(socket){
socket.emit('server emit', { hello: 'server emit' });
socket.on('client emit', function (data) {
console.log("Server received : " + data);
});
});
});
module.exports = router;
and my client script:
var socket = io('http://localhost:2002');
socket.on('connect', function() {
socket.on('server emit', function(data) {
console.log('inside eventtt');
console.log(data);
});
});
But I face this error in my browser console:
socket.io-1.4.5.js:1 GET http://localhost:2002/socket.io/?EIO=3&transport=polling&t=LPajDxI
I think the problem is due to wrong initialization of my socket on the server side, but I don't know how to handle the problem.

Show database content in browser with node.js, MySQL and Jade

I'm currently working with Node.js, Express.js and Jade. My database is MySQL. I'm new to node.js, so I thought I try something very easy: Displaying some data from the database in a table in the browser.
Unfortunately it still doesn't work. I can display data on an free port but not where I need it - on port 3000. And I also can't work with the response itself. This is one of the "solutions" or ideas I had. Maybe there is a problem with the asynchronous call? I simply have no idea.
Here is my code:
routes.js
var express = require('express');
var controller = express.Router();
var dataModel2 = require('../models/rooms');
controller.get('/rooms', function(req, res, next) {
var rooms = dataModel2();
res.render('rooms', {
items: rooms
});
});
module.exports = controller;
models/rooms.js
var rooms;
var connection = require('./databaseConnection');
var http = require('http');
rooms = function() {
http.createServer(function (request, response)
{
console.log('Creating the http server');
connection.query('SELECT * FROM rooms', function(err, rows, fields)
{
response.writeHead(200, { 'Content-Type': 'application/json'});
var room = response.end(JSON.stringify(rows));
return room;
});
});
module.exports = rooms();
models/databaseConnection.js
var mysql = require('mysql');
module.exports = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'raspi_key_royal'
});
rooms.jade
extends layout
block content
div(id="bodyRoyal")
table(border='1')
thead
tr
th ID
th Name
tbody
each item in items
tr
td=item.rid
td=item.name
I splitted the functions a bit because there are some other sections like "persons" etc. I tried to insert console.logs in the rooms.js but that doesn't seem to work.
I also thought I could save the response into a variable so that I can work with it somewhere else.
Thank you for every help and hints!
Steffi
Something like this should do it:
var express = require('express'),
app = express(),
connection = require('./databaseConnection');
app.get('/rooms', function (req, res) {
connection.query('SELECT * FROM rooms', function(err, rows, fields)
{
res.render('rooms', {
items: rows
});
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
This is from the express site...http://expressjs.com/starter/hello-world.html
app.listen(3000, ...
is the how to configure a it to a specific port (in this case 3000).
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});

Setting up a MongoDB database connection with node.js

How would I set up a MongoDB database connection with node.js?
Here is my app.js file:
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.htm');
});
app.use(express.static(__dirname + '/assets'));
io.sockets.on('connection', function(socket) {
socket.on('send message', function(data) {
io.sockets.emit('new message', data);
});
});
I have already set-up MongoDB and have it running as a service on Windows.
As of 1.2, the recommended way to perform a connection is in documentation:
http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html
excerpt:
var MongoClient = require('mongodb').MongoClient
, Server = require('mongodb').Server;
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
var db1 = mongoClient.db("mydb");
mongoClient.close();
});
You may find that a connection singleton is useful for the current state of the official node.js driver. Below is some sample code that I use:
connection.js module:
var MongoClient = require('mongodb').MongoClient;
var db_singleton = null;
var getConnection= function getConnection(callback)
{
if (db_singleton)
{
callback(null,db_singleton);
}
else
{
//placeholder: modify this-should come from a configuration source
var connURL = "mongodb://localhost:27017/test";
MongoClient.connect(connURL,function(err,db){
if(err)
log("Error creating new connection "+err);
else
{
db_singleton=db;
log("created new connection");
}
callback(err,db_singleton);
return;
});
}
}
module.exports = getConnection;
Referencing module:
var getConnection = require('yourpath/connection.js')
function yourfunction()
{
getConnection(function(err,db)
{
//your callback code
}
.
.
.
}

Why can't I see in console.log() the server code of socket.io?

I am starting to learn how to use socket.io and I've been trying to figure this out for the last couple of days but I don't get 2 things.
Why, after starting the server and loading my respective url (localhost:8088) does it take so long for my alert to show up?
Why can't I see the server code of socket.io? for example in the next chunk of code I never see in console my data from "my other event".
server (app.js):
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(8088);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('news', {
hello: 'world'
});
socket.on('my other event', function (data) {
console.log(data);
});
});
client (index.html):
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('news', function (data) {
console.log(data);
alert(data.hello);
socket.emit('my other event', {
my: 'data'
});
});
</script>
It might be the incompability between express 3.0 and socket.io
Try this:
var express = require('express'),;
var http = require('http');
var app = express();
var server = module.exports = http.createServer(app);
var io = require("socket.io").listen(server);
server.listen(8088);

Categories

Resources