connecting two apps using socketIO - javascript

I have implemented a user interface to do some wizard of oz testing. I have a user-side page (Page A), and a second page, the wizard page (Page B). They use the same data and page B receives some information from page A to load the correct data. When the user asks questions on page A, the question is sent to page B, and an answer should be sent back to page A. The problem is that Page A is open on device A and page B is open on Device B (both are on the same server).
I am trying to implement the communication between page A and page B using socketIO. I searched for hours and didn't find a complete example of connecting two apps using socketIO. They usually open the same app in multiple windows. That won't help me. My understanding so far is that I should create a server for each app, and then have the two servers communicate with each other. What I have so far doesn't work and no communication is happening. What I have is as follow:
for page A (index.html):
I added a index.js server file:
// Import packages
const express = require("express");
const socketIO = require("socket.io");
const path = require("path");
// Configuration
const PORT = process.env.PORT || 3000;
//const INDEX = path.join(__dirname, 'index.html');
const INDEX = path.join(__dirname, 'index.html');
console.log("INDEX", INDEX);
//const WIZARD = path.join(__dirname, 'wizard.html');
// Start server
const server = express()
//.use((req, res) => res.sendFile(INDEX), (req, res) => res.sendFile(WIZARD))
.use((req, res) => res.sendFile(INDEX))
.listen(PORT, () => console.log("Listening on localhost:" + PORT));
// Initiatlize SocketIO
const io = socketIO(server);
var other_server = require("socket.io-client")('http://localhost:4000');
other_server.on("connect",function(){
other_server.on('message',function(data){
// We received a message from Server 2
// We are going to forward/broadcast that message to the "Lobby" room
io.to('lobby').emit('message',data);
});
});
io.sockets.on("connection",function(socket){
// Display a connected message
console.log("User-Client Connected!");
// Lets force this connection into the lobby room.
socket.join('lobby');
// Some roster/user management logic to track them
// This would be upto you to add :)
// When we receive a message...
socket.on("message",function(data){
// We need to just forward this message to our other guy
// We are literally just forwarding the whole data packet
other_server.emit("message",data);
});
socket.on("disconnect",function(data){
// We need to notify Server 2 that the client has disconnected
other_server.emit("message","UD,"+socket.id);
// Other logic you may or may not want
// Your other disconnect code here
});
});
For the same app, to the index.html I added the following script:
<script type="text/javascript">
// Get WebSocket
var socket = io.connect('http://localhost:3000');
// Client
socket.on('connect', function(){
socket.emit("message","This is my message");
socket.on('message',function(data){
console.log("We got a message: ",data);
});
});
// Join a channel
var room = "test";
socket.emit("join", room);
let msg = "hello helloo helloooo from index.html";
socket.emit("new_message", msg);
socket.on("new_message", function (msg) {
console.log("sending a message through server from index.html", msg);
});
</script>
For the second app, wizard.html I added a server file, index.js:
// Import packages
const express = require("express");
const socketIO = require("socket.io");
const path = require("path");
// Configuration
const PORT = process.env.PORT || 4000;
//const INDEX = path.join(__dirname, 'index.html');
const INDEX = path.join(__dirname, 'wizard.html');
console.log("INDEX", INDEX);
//const WIZARD = path.join(__dirname, 'wizard.html');
// Start server
const server = express()
//.use((req, res) => res.sendFile(INDEX), (req, res) => res.sendFile(WIZARD))
.use((req, res) => res.sendFile(INDEX))
.listen(PORT, () => console.log("Listening on localhost:" + PORT));
// Server 2
const io = socketIO(server);
io.sockets.on("connection",function(socket){
// Display a connected message
console.log("Server-Client Connected!");
// When we receive a message...
socket.on("message",function(data){
// We got a message. I don't know, what we should do with this
});
});
and to the wizard.html, I added the script below:
<script type="text/javascript">
// Get WebSocket
//var socket = io();
var socket = io.connect('http://localhost:4000');
// Join a channel
var room = "test";
socket.emit("join", room);
let msg = "hello helloo helloooo from wizard";
socket.emit("new_message", msg);
socket.on("new_message", function (msg) {
console.log("sending message through server from wizard", msg);
});
/*
*/
</script>
I also added <script src="/socket.io/socket.io.js"></script> to both apps, index.html, and wizard.html.
In wizard.html I get this error:
POST http://localhost:4000/socket.io/?EIO=3&transport=polling&t=OAp7bZr 400 (Bad Request)
and in index.html I get this error:
Access to XMLHttpRequest at 'http://localhost/socket.io/?EIO=3&transport=polling&t=OAp7k5w' from origin 'http://localhost:3000' has been blocked by CORS policy:
If you can help me figure out what I am missing or if you know of any complete working example similar to what I am trying to accomplish, I would very much appreciate it if you let me know.
It would be even more helpful if someone could use the code and scenario I provided here and write a minimum working example in which the two apps, a.html, and b.html, can communicate through socketIO.

Related

Heroku Sockets Javascript

I have the following example using Node.js for the server that sends data via Socket.io to a Javascript file. All works well locally, but when I uploaded to Heroku, it does not. I have tried a lot of tips I found online, but I am always stuck and can't get it through. At the moment, I don't get errors, but I also can't see the values coming through.
Here is the code I use at the moment:
var express = require('express');
var socket = require('socket.io');
//store the express functions to var app
var app = express();
//Create a server on localhost:3000
var server = app.listen(process.env.PORT || 3000);
//var server = app.listen((process.env.PORT || 3000, function(){
//console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
//});
//host content as static on public
app.use(express.static('public'));
console.log("Node is running on port 3000...");
//assign the server to the socket
var io = socket(server);
//dealing with server events / connection
io.sockets.on('connection', newConnection); //callback
//function that serves the new connection
function newConnection(socket){
console.log('New connection: ' + socket.id);
socket.on('incomingDataToServer', emitFunction);
function emitFunction(data){
//setInterval(() => socket.broadcast.emit('ServerToClient', new Date().toTimeString()), 1000);
let randNum;
setInterval(function(){
//get a random value, and assign it a new variable
randNum = getRandomInt(0, 100);
}, 1000);
socket.broadcast.emit('ServerToClient', randNum);
//following line refers to sending data to all
//io.sockets.emit('mouse', data);
console.log(randNum);
}
}
And the Javascript here:
let socket;
socket = io();
socket.on('ServerToClient', socketEvents);
function socketEvents(data){
incomingData = data;
console.log(data);
}
Any help is appreciated.
Thanks
Write app.use before the app listen
and modify app.listen as below and check heroku logs for console message.
app.use(express.static('public'));
var server = app.listen(port, function() {
console.log('Server running on ' + port + '.');
});
if It still not work let me know.

Node.js server hangs occasionally

I have this node.js server. The problem is sometimes I notice that it gets stuck. That is the client can make requests, but the server doesn't respond, rather it doesn't end the response, it just gets stuck in the server side. If I look in client side dev tools on the http request, it has a gray circle icon meaning waiting for server response. Even if I wait 10 minutes, nothing happens.
The server side also writes things to console on the requests, which doesn't happen when it gets stuck.
On the node.js console, if I then press ctrl+c when it got stuck, I then suddenly see all the console.log messages just appear on the console, and at the same time, the dev tools, recieves all the responses from the server side, i.e. the gray circle changes to green.
Does anyone know what this problem is?
Thanks
var express = require('express');
var https = require("https");
var fse = require("fs-extra");
var bodyParser = require('body-parser');
// INFO
var root = __dirname + '/public';
setUpServer();
// SET UP SERVER
function setUpServer() {
var app = express();
app.use(express.static(root));
app.use(bodyParser.urlencoded({ extended: false }))
app.get('/', function (req, res) {
var dest = 'index.html';
res.sendFile(dest, { root: root + "/pong" });
});
app.post('/get_brain', function (req, res) {
res.end("1");
console.log('Sent master brain to a client!');
});
app.post('/train_and_get_brain', function (req, res) {
res.end("1");
console.log('Sent master brain to a client!');
});
var privateKey = fse.readFileSync('sslcert/key.pem', 'utf8');
var certificate = fse.readFileSync('sslcert/cert.pem', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var httpsServer = https.createServer(credentials, app);
httpsServer.listen(process.env.PORT || 3000, function () {
var host = httpsServer.address().address;
var port = httpsServer.address().port;
console.log('AI started at https://%s:%s', host, port);
});
}

Single object of socket IO

I am trying to create an application based on socket. Looking at the console it can be said that the client to trying to socket server twice; which should not be allowed.
Is there any way to stop that?
If have modular javascript file where multiple script want to access same socket connection how is that possible?
<!DOCTYPE html>
<html>
<head>
<title>socket</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
</head>
<body>
<script type="text/javascript">
$(function(){
var socket = io();
console.log(typeof socket); // object
var socket1 = io();
console.log(socket === socket1); // false
})
</script>
</body>
</html>
Don't connect the client to socket twice....
A global variable will allow you to access the socket from all your script files
Eg)
//you can access this variable from all your scripts
var socket;
$(function(){
socket = io();
console.log(typeof socket);
})
Note that in javascript polluting the global scope with variables and functions is considered bad practice, but that's for another post.
The obvious suggestion is to stop having your client connect twice.
But, if you're trying to prevent multiple connections on the server and you really don't want any end user to be able to use more than one window at a time to your web site, then you can prevent another connection once there is already a connection.
The key would be to identify each browser with some sort of unique cookie (user ID or uniquely generated ID number). You can then implement socket.io authentication that keeps track of which user IDs already have a connection and if a connection is already live, then subsequent attempts to connect will fail the authentication step and will be disconnected.
Supposed you have a cookie set for each browser that's called userId. Then, here's a sample app that makes sure the userId cookie is present and then uses it to deny more than one socket.io connection:
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const cookie = require('cookie');
app.use(cookieParser());
let userIdCntr = 1;
const tenDays = 1000 * 3600 * 24 * 10;
app.use(function(req, res, next) {
// make sure there's always a userId cookie
if (!req.cookies || !req.cookies.userId) {
// coin unique user ID which consists of increasing counter and current time
let userId = userIdCntr++ + "_" + Date.now();
console.log("coining userId: " + userId);
res.cookie('userId', userId, { maxAge: Date.now() + tenDays , httpOnly: true });
}
next();
});
app.get('/test.html', function (req, res) {
console.log('Cookies: ', req.cookies)
res.sendFile( __dirname + "/" + "test.html" );
});
const server = app.listen(80);
const io = require('socket.io')(server);
// which users are currently connected
var users = new Set();
// make sure cookie is parsed
io.use(function(socket, next) {
if (!socket.handshake.headers.cookieParsed) {
socket.handshake.headers.cookieParsed = cookie.parse(socket.handshake.headers.cookie || "");
}
next();
});
// now do auth to fail duplicate connections
io.use(function(socket, next) {
console.log("io.use() - auth");
// if no userId present, fail the auth
let userId = socket.handshake.headers.cookieParsed.userId;
if (!userId) {
next(new Error('Authentication error - no userId'));
return;
}
// if already logged in
if (users.has(userId)) {
console.log("Failing user " + userId);
next(new Error('Authentication error - duplicate connection for this userId'));
return;
} else {
console.log("adding user " + userId);
users.add(userId);
}
next();
});
io.on('connection', function(socket) {
console.log("socket.io connection cookies: ", socket.handshake.headers.cookieParsed);
socket.on('disconnect', function() {
console.log("socket.io disconnect");
let userId = socket.handshake.headers.cookieParsed.userId;
users.delete(userId);
});
// test message just to see if we're connected
socket.on("buttonSend", function(data) {
console.log("buttonSend: ", data);
});
});
P.S. You really have to think through the situation where a user with more than one computer (like home/work) leaves one computer on and open to your page and thus connected via socket.io and then attempts to user your site from the other computer. If you refused the second connection, this will refuse to allow them access from their second computer if the first computer happened to be left open and on.

Prime the website using Express JS

I really hope to find some answers here as i tried everything by now.
Background:
Overtime we deploy code to web server, we need to do a cache warm up, i.e. access the site and make sure it loads. First load is always the slowest since IIS require to do some manipulations with a new code and cache it.
Task:
Create a page which will a checkbox and a button. Once button is pressed, array of links sent to server. Server visits each link and provides a feedback on time it took to load each page to the user.
Solution:
I am using node JS & express JS on server side. So far i manage to POST array to the server with links, but since i have limited experience with node JS, i can not figure out server side code to work.
Here is a code i got so far (it is bits and pieces, but it gives an idea of my progress). Any help will be greatly appreciated!!!
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var parseUrlencoded = bodyParser.urlencoded({ extended: false});
var http = require("http");
function siteToPrime(url){
http.get(url, function (http_res) {
// initialize the container for our data
var data = "";
// this event fires many times, each time collecting another piece of the response
http_res.on("data", function (chunk) {
// append this chunk to our growing `data` var
data += chunk;
});
// this event fires *one* time, after all the `data` events/chunks have been gathered
http_res.on("end", function () {
// you can use res.send instead of console.log to output via express
console.log(data);
});
});
};
//Tells express where to look for static content
app.use(express.static('public'));
app.post('/', parseUrlencoded, function(request, response){
var newBlock = request.body;
console.log(Object.keys(newBlock).length);
var key = Object.keys(newBlock)[0];
console.log(newBlock[key]);
siteToPrime("www.google.com");
response.status(201);
});
app.listen(3000, function(){
console.log("Server listening on port 3000...");
});
Assuming that you have access to the array in the post route:
var express = require("express"),
request = require("request"),
app = express();
var start = new Date();
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: false}));
function siteToPrime(req, res, urls) {
urls.forEach(function(url)) {
request(url, function(error, res, body) {
if (!error && res.statusCode == 200) {
console.log(url +' : ' + body);
console.log('Request took: ', new Date() - start, 'ms');
}
});
}
res.redirect('/');
};
app.post('/', function(req, res){
var urls = req.body.urls // Array os urls.
siteToPrime(req, res, urls);
});
app.listen(3000, function(){
console.log("Server listening on port 3000...");
});

node.js : Express, socket.io and PostgreSQL

I am using Express, node.js and socket.io. What I would like to implement is a system in which everytime a user connects to the page (upon 'connection' event), an SQL request is performed so the results are emitted to the user by trigerring the event 'get_recipes'. However, after refreshing the page several times, the event 'get recipes' is not triggered anymore... Can someone tell me what is wrong with my code (do I need to log out from the database ? If so, how ?) ? Thanks a lot !
app.js :
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var pg = require('pg').native;
var db_URL = "tcp://user1:default#localhost/dbtest";
...
io.sockets.on('connection', function (socket) {
pg.connect(db_URL, function(err, client) {
client.query("SELECT * FROM Recipes", function(err, results) {
socket.emit('get_recipes', results);
});
});
});

Categories