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.
Related
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:.
I am working with socket.io , so i created server on app.js and connect socket to client and i see emit('message') is printing to the client console, Now i want to send another message from different file consumer.js and emit message to client but its throwing exception on server side io.on is not a function. Any idea what is implemented wrong in consumer.js file ?
app.js
var express = require('express');
var app = express();
var consumer = require('./consumer');
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.use(express.static(__dirname + "/public"));
io.on('connection', function(client) {
console.log('Client connected...');
client.emit('message', ' hello from server');
});
server.listen(3000, function () {
console.log('Example app listening on port 3000!');
consumer.start();
});
consumer.js
var io = require('socket.io');
function startConsumer(consumer) {
consumer.on('message', function (message) {
logger.log('info', message.value);
io.on('connection', function(client) {
console.log('Consumer connected...');
client.emit('Consumer-Message', 'Message from dit consumer');
});
});
consumer.on('error', function (err) {
console.log('error', err);
});
};
exports.start = start;
angularCtrl.js
socket.on('message',function (data) {
console.log(data);
});
socket.on('Consumer-Message',function (data) {
console.log(data);
});
I am trying around with nodejs and socket.io
But my application refuses to work after a few requests. It takes a while and after some time it starts working again.
Here is the code for the nodejs-server, where i expect the issue.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('db.sqlite');
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 8080;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var router = express.Router();
router.post('/', function (req, res) {
res.sendFile(__dirname + "/app/index.html");
});
router.get('/sample', function (req, res) {
res.sendFile(__dirname + "/app/sample.html");
});
router.post('/api/error', function (req, res) {
var data = req.body;
data.date = Date();
io.emit('error', JSON.stringify(data));
res.header("Access-Control-Allow-Origin", "*");
});
io.on('connection', function(socket){
console.log('a client connected');
});
app.use('', router);
app.use(express.static('app'));
app.use('/static', express.static('node_modules'));
// START THE SERVER
server.listen(port);
console.log('Magic happens on port ' + port);
The applikation is for monitoring errors in a full webstack.
The handler for POST /api/error isn't sending back a response, so the client will continue to wait. At some point, it may decide not to open any more connections to the server until the previous ones have been answered (or have timed out).
You can just send back a 200 response:
router.post('/api/error', function (req, res) {
var data = req.body;
data.date = Date();
io.emit('error', JSON.stringify(data));
res.header("Access-Control-Allow-Origin", "*").sendStatus(200);
});
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");
....
I have an app with express (nodeJS).
Want to emit io.socket when write some data on DB, so need to emit in route file (ex. /routes/save.js)
this is my app.js
var express = require('express');
var save = require('./routes/save');
var http = require('http');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
......
io.on('connection', function(socket){
socket.on('newTweet', function(msg){
io.emit('newTweet', msg);
});
});
app.use('/save', save);
.....
module.exports = app;
server.listen(3000, function () {
var host = server.address().address
var port = server.address().port
})
Can you please help me to write io.socket.emit('event') in /routes/save.js ?
I found a way.
Before app.use('/save', save); needed to write following code in app.js
app.use(function(req, res, next) {
req.io = io;
next();
});
and after this get io from req parameter in save.js
for example
var express = require('express');
var router = express.Router();
router.post('/', function(req, res, next) {
.....
var io = req.io;
io.emit('newTweet', 'test');
.....
});
module.exports = router;
if you know better way than this one, please let me know.
You can just pass the io object to your routes like this:
var app = express();
var io = socket_io();
app.io = io;
require('./routes/index')(app,io);
import {createServer} from 'http';
import express from 'express';
import socketio from 'socket.io';
const server = createServer(app);
const io = socketio.listen(server);
app.use(function (req, res, next) {
req.io = io;
next();
})
app.get('/', function (req, res) {
const ioConnection = req.io;
ioConnection.emit('nouveau_client', body.pseudo);
});
io.sockets.on('connection', function (socket) {
socket.on('nouveau_client', function (user) {
socket.broadcast.emit('nouveau_client', user.pseudo);
});
});
server.listen(3000);