How to emit message using socket.io from two different files? - javascript

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);
});

Related

Having Trouble Running my Server.JS. Listening Error

Hello I am having trouble starting up my server.js. Every time that I would run node towards it. It wills always show this error "listening on *:3000". Here is my code for my server.js.
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/chat', (req, res) => {
res.sendFile(__dirname + '/chat.html');
});
io.on('connection', (socket) => {
console.log('User Online');
socket.on('codeboard-message', (msg) => {
console.log('message: ' + msg);
socket.broadcast.emit('message-from-others', msg);
});
});
var server_port = process.env.YOUR_PORT || process.env.PORT || 3000;
http.listen(server_port, () => {
console.log('listening on *:' + server_port);
});
Do I have to use a different port or am I missing a line of code for this server to work? Any help will be appreciated!
var app = require('express')();
var http = require('http').createServer(app);
var server_port = process.env.PORT || 3000;
http.listen(server_port, () => {
console.log('listening on *:' + server_port);
});
try only this without socket io. If it works, add socket io code

how to request the url in socket.io

I am trying get the json data from url example.com and pass that to my index.html. How can I do that. It's not working. I want to update data every 5 second file index.html.
app.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var https = require('https');
app.get('/', function(req, res) {
res.sendfile('index.html');
//How to use req object ?
});
io.on('connection', function(socket) {
console.log('A user connected');
setInterval(function() {
urlString = "https://example.com/trip?trip_id=1234";
$.get(urlString, function(data, status){
console.log('data');
})
socket.send('');
}, 4000);
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('message', function(data){document.write(data)});
</script>
You were doing a number of things wrong:
$.get() doesn't run on the server. That's client-side jQuery code
You should create one setInterval() on your server, not a new one for each client connection
You can then just broadcast the results to all connected clients
If you document.write() in the client after the page is loaded, it just clears your original document so you want to append info to the DOM, not use document.write().
When you send data with socket.io, you send a message name and some data .emit(someMessage, someData).
Here's one way to do your code:
// server.js
const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const request = require('request');
app.get('/', function(req, res) {
res.sendfile('index.html');
});
// create one and only one interval
setInterval(function() {
let urlString = "https://example.com/trip?trip_id=1234";
request(urlString, function(err, response, data) {
if (err) {
console.log("error on request", err);
} else {
console.log('data');
// send to all connected clients
io.emit('message', data);
}
});
}, 5000);
io.on('connection', function(socket) {
console.log('A user connected');
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
server.listen(3000, function() {
console.log('listening on *:3000');
});
// index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('message', function(data){
let div = document.createElement("div");
div.innerHTML = data;
document.body.appendChild(div);
});
</script>

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.

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