I have this index.js file on the client:
var socket;
var init = function() {
// Setup Socket:
socket = io.connect();
// Setup Event Handlers:
setEventHandlers();
// Connect to Server:
socket.emit('connect', {
name : "User Name"
});
console.log("Client Init Complete.");
}
var setEventHandlers = function() {
// Set Routes For Connections
socket.on("connection resp", onConnected);
}
var onConnected = function(data) {
console.log(data.resp);
}
And I have this code on the server:
// SETUP:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var request = require('request');
var path = require('path');
var socket = require('socket.io')(http);
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0';
var bodyParser = require('body-parser')
var fs = require('fs');
// SETUP:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended : false
}));
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
})
var setEventHandlers = function() {
socket.sockets.on("connection", onInit);
};
var onInit = function(client) {
client.on("connect", onConnect);
};
var onConnect = function(data) {
console.log("Called");
}
// Send index page html
app.get('/', function(req, res) {
res.sendfile("public/html/index.html");
});
// Turn on server
http.listen(server_port, server_ip_address, function() {
console.log("App Listening on " + server_ip_address + ", server_port "
+ server_port);
});
setEventHandlers();
The issue is that on the onConnect on the server is never called. Eventhough I call socket.emit("connect") on the client.
After further testing, it seems that the socket id is undefined: this.id returns undefined.
You need to add quotes to the parameters in the socket.emit function like this:
// Connect to Server:
socket.emit('connect', {
'name' : 'User Name'
});
You should initialize your socket variable through io.connect("server address") and has i see in your code you have not passed any parameter to io.connect
.If server is in your local machine then connect to it by io.connect("http://localhost").
For more information see Docs. socket.io-client
Related
I have a file on main root as
test_file.js
Following is the code inside it
var config = require('config');
var Ctrl = require('./Controllers');
var port = process.env.PORT || config.get("PORT") || 3000;
var cors = require('cors');
var express = require('express');
var app = express();
var router = express.Router();
app.use(cors());
app.use(router);
var server = require('http').createServer(app);
var io = require('socket.io')(server, {'pingInterval': 4000, 'pingTimeout': 6000});
io.on('connection', Ctrl.connection);
console.log("Opening at port " + port);
server.listen(port, function () {
});
module.exports = router;
require('./Routes')();
I have another file in path
/Controllers/index.js
i want to pass out io to index.js too, here is its code
var Promise = require('q').Promise;
var config = require('config');
var mysql = require('mysql');
/// I want to get var io = require('../test_file.js');
/**Initialization socket connection */
exports.connection = function (socket) {
if (!(socket.handshake.query.accountType != null && socket.handshake.query.id != null && socket.handshake.query.accessKey != null
&& socket.handshake.query.id > 0)) {
socket.disconnect();
return;
}
Now i am confused about module.exports and exports, my module.exports is already passing out to another file, i want to add another variable i-e io and pass it to controllers file. How can i do that
In respond to the query,
app.use(router);
var server = require('http').createServer(app);
var io = require('socket.io')(server, {'pingInterval': 4000, 'pingTimeout': 6000});
module.exports = {
router: router,
io: io
};
io.on('connection', Ctrl.connection);
console.log("Opening at port " + port);
server.listen(port, function () {
});
require('./Routes')();
In Controllers/index.js
var Promise = require('q').Promise;
var config = require('config');
var mysql = require('mysql');
var Driver = require('./driver');
var User = require('./user');
var io = require('../test_file.js').io;
console.log("logging");
console.log(io);
the result is {} for io
exports is just module.exports's little helper. Your module returns module.exports to the caller ultimately, not exports. All exports does is collect properties and attach them to module.exports IF module.exports doesn't have something on it already. If there's something attached to module.exports already, everything on exports is ignored.
you can pass both as the object
module.exports = {
router: router,
io: io
};
Please refer this doc for more explanation
Edit
Access object via module.exports
file.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = {router:router};
Acess it with
var router=require('./file').router
OR
var router=require('./file');
router.router
How can i read cookie on node js ??
var socket = require( 'socket.io' );
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen( server );
var port = process.env.PORT || 8000;
var mysql = require('mysql');
function parseCookies (request) {
var list = {},
rc = request.headers.cookie;
rc && rc.split(';').forEach(function( cookie ) {
var parts = cookie.split('=');
list[parts.shift().trim()] = decodeURI(parts.join('='));
});
return list;
}
http.createServer(function (request, response) {
// To Read a Cookie
var user_id= cookies.realtimeid;
console.log(user_id);
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
var cookies = parseCookies();
console.log(cookies);
});
I am new on node and socket. I have to read cookie value that is set by codeignter.
How can i send header request on parseCookies from server.listen.
I see you are using express, so I suggest you to use the very well known module for it. cookie-parser https://www.npmjs.com/package/cookie-parser
Installation
npm install cookie-parser
HOW TO USE IT
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
So basically after your mysql require you can do app.use(cookieParser())
And then in every request you do in the req variable you will find the cookies with req.cookies
Example
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies)
})
app.listen(8080)
I am having problems with Middleware to get the handshake.session in socket.io module to work properly with even a simple example.
1.- I have some error in the cod
how can be solved
2.- please just need
get handshake session
Thanks
I am just trying to get this example to work:
const KEY = 'express.sid'
, SECRET = 'express';
var express = require('express'), app = express()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server)
, cookie = express.cookieParser(SECRET)
, store = new express.session.MemoryStore()
, session = express.session({secret: SECRET, key: KEY, store: store});
app.configure(function(){
app.set('view engine', 'ejs');
app.use(cookie);
app.use(session);
});
app.get("/", function(req, res){req.session.ID = "U"+2;});
server.listen(3000);
io.set('authorization', function(data, accept) {
cookie(data, {}, function(err) {
if (!err) {
var sessionID = data.signedCookies[KEY];
store.get(sessionID, function(err, session) {
if (err || !session) {
accept(null, false);
} else {
data.session = session;
accept(null, true);
}
});
} else {
accept(null, false);
}
});
});
io.sockets.on('connection', function (socket) {
var session = socket.handshake.session, id = session.ID;
console.log(id);
});
Having issues with app.configure:
debugger;
var appSettings = require('./server/config/settings/MainAppSettings.js');
// ====== DB ==============
//var sqlImport = require('./server/dbConnectors/MYSQL/MYSQLMainConn.js');
//var dbConnection = new sqlImport.sqlConn();
var dbConnection = null;
// ====== setup basic server ==============
var root = __dirname;
var express = require('express');
var app = express();
app.configure(function () {
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.errorHandler({dumbExceptions:true, showStack:true}));
});
// ====== SSL ==============
var https = require('https');
var fs = require('fs');
// This line is from the Node.js HTTPS documentation.
var options = {
key: fs.readFileSync(appSettings.key1.key),
cert: fs.readFileSync(appSettings.key1.cert)
};
// ====== Routes ==============
//handle get requests
var errors = require('./server/errors/errors.js').errors;
require('./server/config/routes/routes.js')(app, dbConnection, errors);
//keep server from crashing by catching all exceptions not caught before
process.on('uncaughtException', function(err) {
console.log(err);
});
//launch http server
app.listen(appSettings.ports.http);
console.log('Express http server listening on port %d in %s mode',appSettings.ports.http, app.settings.env);
//launch https server
https.createServer(options, app).listen(appSettings.ports.https, function(){
console.log('Express https server listening on port %d in %s mode',appSettings.ports.https, app.settings.env);
});
module.exports = app;
Seems like you are using Express 4.0 in which configure was removed.
See http://expressjs.com/guide/migrating-4.html#other-changes
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
}
.
.
.
}