how to request the url in socket.io - javascript

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>

Related

Cannot send message to client in nodejs with socket.io

I have 2 pages: play page, live page and server. I want to use socket.io to do this: i want to send data from play page to server and then to live and show a text that update automatically when I change it in play page.
play page emit this
var n = <%-JSON.stringify(v1)%>;
var socket = io.connect('http://localhost:3000');
socket.emit('event', { message: n });
server code
var server = app.listen(3000); //port 3000 is only for sockets. my app has web traffic on port 5000.
var io = require('socket.io')(server);
io.on('connection', function(socket) {
socket.on('event', function(data) {
console.log('A client sent us this dumb message:', data.message);
var n = data.message;
console.log("");
console.log("data received from play client..trying to send to live");
console.log("");
console.log("var n is");
console.log(n);
console.log("sending data...");
socket.emit('event', { message: n });
Whatever I do in live page it don't receive message.
I solved 50% of my problem creating another socket in server.js that listen to port 3002 and this worked. But now my content don't update automatically on live page. I have to refresh manually and I don't want this.
This is my new server.js code that worked(without realtime update on live.ejs page):
const express = require('express');
const store = require('./store');
const storeLyric = require('./storeLyric');
const searchF = require('./search');
// middleware to handle HTTP POST request
// extract the entire body portion of an incoming request and exposes it on req.body
const bodyParser = require('body-parser');
const app = express();
app.set('port', (process.env.PORT || 5000));
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
///new
var server = app.listen(3000);
var io = require('socket.io')(server);
var server2 = app.listen(3002);
var io2 = require('socket.io')(server2);
io.on('connection', function(socket) {
socket.on('event', function(data) {
console.log('A client sent us this dumb message:', data.message);
var n = data.message;
console.log("");
console.log("data received from play client..trying to send to live");
console.log("");
console.log("var n is");
console.log(n);
console.log("sending data...");
io2.on('connection', function(socket2) {
socket2.on('live', function(data2) {
console.log('status from live client:', data2);
socket2.emit('live', n);
});
});
////////////////////
});
});
//end new
////////////
// default page
app.get('/', (req,res) => {
let students = [];
var end = req.query.end;
if(end==1 || end==2){
io2.on('connection', function(socket2) {
socket2.on('live', function(data2) {
console.log('status from live client:', data2);
socket2.emit('live', '');
});
});
}
store.studentList().then((req,respond) => {
students = req;
res.render('pages/index', {
title: '',
students:students
})
})
})
//live page
app.get('/live', function (req, res) {
res.render('pages/live', {
n:'gsgs'
})
})
// search page
app.get('/search', (req,res) => {
let search = [];
var q = req.query.q; // $_GET["q"]
searchF.search(q).then((req,respond) => {
search = req;
res.render('pages/search', {
search:search,
q:q
})
})
})
// play page
app.get('/play', (req,res) => {
let lyrics = [];
var vers = req.query.vers; // $_GET["vers"]
var for_id = req.query.for_id; // $_GET["vers"]
storeLyric.lyrics(for_id, vers).then((req,respond) => {
lyrics = req;
res.render('pages/play', {
title: '',
lyrics:lyrics
})
});
////////
})
app.listen(app.get('port'), () => {
console.log("Listening to port: ", app.get("port"))
});
What I'm doing wrong and why socket.io doesn't work in realtime?
Thanks for help!
You need to emit the event from server side to the client side and then catch data there
var server = app.listen(3000);
var io = require('socket.io')(server);
io.on('connection', function(socket) {
socket.on('event', function(data) {
var n = data.message;
io.sockets.emit('event', message);
});
And then on frontend in live page you write this
var n = <%-JSON.stringify(v1)%>;
var socket = io.connect('http://localhost:3000');
socket.on('event', (data)=>{
console.log(data)
});

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.

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

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

Node.js Socket.io seperate connection events for each page

I've taken the following code from Socket.io documentations page.
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
app.use(express.static(__dirname + '/public'));
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
I would like to have a separate 'connection' event depending on the page that made the request. E.g.
Clients connected from the 'index' page trigger this event.
io.on('connection', function (socket) {
console.log('connected from the index page');
});
and
clients connected from the 'player scores' page trigger this event
io.on('connection', function (socket) {
console.log('connected from the index page');
});
I've considered using namespaces. Is there a way that I could do this without out the client having to specify that it has connected from a particular page?
Regards,
You could use the handshake data in the socket object to get the URL and then program the different pieces of logic in an if-statement. Something along these lines:
io.on('connection', function (socket) {
if(socket.handshake.url == "index url you expect"){
console.log('connected from the index page');
} else if(socket.handshake.url == "player scores url you expect"){
console.log('connected from the player scores page');
}
});

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