NodeJS Ajax requests working exactly seven times - javascript

I'm currently learning JavaScript / NodeJS / electron, and I want to build a small presenter-app to remotely control powerpoint-presentations.
I've setup a server using electron like this:
const electron = require('electron');
const robot = require("robotjs");
const fs = require('fs');
const express = require('express');
const cors = require('cors');
const {
app,
BrowserWindow
} = electron;
var mainWin = null;
var contentString;
app.on('ready', function() {
mainWin = new BrowserWindow({
width: 800,
height: 600
});
contentString = "";
// Remove Menu-Bar
mainWin.setMenu(null);
const port = 3000;
var app = express();
app.use(cors());
app.post('/remote/forward', function(request, response, next) {
var ip = getRemoteIP(request);
log(mainWin, "presenter - forward");
robot.keyTap("right");
});
app.post('/remote/backward', function(request, response, next) {
var ip = getRemoteIP(request);
log(mainWin, "presenter - backward");
robot.keyTap("left");
});
app.listen(port, function() {
log(mainWin, 'server listening on port ' + port);
});
});
function log(mainWin, text) {
contentString += getFormattedDate() + " " + text;
contentString += "<br />";
mainWin.loadURL("data:text/html;charset=utf-8," + encodeURI(contentString));
}
I call these with two js-functions:
function sendForwardRequest() {
$.ajax({
type: 'POST',
data: {
blob: {action:"forward"}
},
contentType: "application/json",
dataType: 'json',
url: 'http://192.168.2.110:3000/remote/forward',
success: function(data) {
console.log('success');
},
error: function(error) {
console.log("some error in fetching the notifications");
}
});
}
function sendBackwardRequest() {
$.ajax({
type: 'POST',
data: {
blob: {action:"backward"}
},
contentType: "application/json",
dataType: 'json',
url: 'http://192.168.2.110:3000/remote/backward',
success: function(data) {
console.log('success');
},
error: function(error) {
console.log("some error in fetching the notifications");
}
});
}
I'm sure that this solution is quite miserble, as I said, I'm currently learning this. My question now is: This works for exactly seven times. After that, I have to reload my clients browser. How can I fix this? Also, what would be a better solution for the requests? I'd like to have only one app.post()-method and use the given post-parameters instead. Last question: What could be a nicer method for the logging? I'd like to append content to my window instead of having to reload the whole string each time.
Thank you very much!

this is the minified version of your code. try and see if it still only fires 7 times
/* Server side */
// instead of two app.post functions, use this one
app.get('/remote/:key', function(request, response, next) {
var ip = getRemoteIP(request);
log(mainWin, "presenter - " + request.params.key);
robot.keyTap(request.params.key);
response.send(request.params.key + ' key pressed');
});
/* Client Side */
function sendKey(key) {
return $.get('http://192.168.2.110:3000/remote/' + key)
}
// to send right key
sendKey('right').done(function(response) { /*success*/ }).fail(function(error) { /*error*/ });

Related

Socket.IO emit not sending

I am currently building a game using Socket.IO and Javascript. I originally wanted to make a real-time multiplayer game, however, I ran into a problem really quick. I eventually gave up and moved to a turn-based game but the problem still didn't go away.
The problem is that the server (app.js) is not getting emits from the client (game.js). I've tried recreating the project, console.log, and search google to no avail.
App.js
require('./Database');
var express = require('express');
var app = express();
var serv = require('http').Server(app);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client', express.static(__dirname + '/client'));
serv.listen(process.env.PORT || 2000);
console.log("Server started.");
var SOCKET_LIST = {};
var io = require('socket.io')(serv, {});
io.sockets.on('connection', function(socket) {
socket.id = Math.random();
SOCKET_LIST[socket.id] = socket;
socket.on('signIn', function(data) { // {username,password}
Database.isValidPassword(data, function(res) {
if (!res)
return socket.emit('signInResponse', { success: false });
Database.getPlayerProgress(data.username, function (progress) {
socket.emit('signInResponse', {
success: true, username: data.username,
progress: progress
});
})
});
});
socket.on('signUp', function(data) {
Database.isUsernameTaken(data, function(res) {
if (res) {
socket.emit('signUpResponse', { success: false });
} else {
Database.addUser(data, function() {
socket.emit('signUpResponse', { success: true });
});
}
});
});
socket.on('disconnect', function() {
delete SOCKET_LIST[socket.id];
});
socket.on("findMatch", function(data) {
console.log('test'); // ******* Not working ********
});
});
Game.js
var socket = io("127.0.0.1:2000");
function findMatch(data) {
socket.emit("findMatch", { socket: socket });
}
FindMatch() is called from the lobby "Find Match" Button. It is hooked up to an onclick listener.
Thank you. I would appreciate any help.
Edit: The connection, sign In, register, and disconnect emits DO work only custom ones I add later (findMatch for example) don't work

Using Server Sent Events with express

I'll try to make this as simple as possible so i'm not having to post a ton of code. Heres what my app does right now:
User uploads an audio file from the browser
That file is processed on my server, this process takes some time and has about 8 or so steps to complete.
Once everything is finished, the user gets feedback in the browser that the process is complete.
What I want to add to this, is after every step in the process that is completed, send some data back to the server. For example: "Your file is uploaded", "Meta data processed", "image extracted" etc etc so the user gets incremental feedback about what is happening and I believe Server Sent Events can help me do this.
Currently, the file is POSTed to the server with app.post('/api/track', upload.single('track'), audio.process). audio.process is where all the magic happens and sends the data back to the browser with res.send(). Pretty typical.
While trying to get the events working, I have implemented this function
app.get('/stream', function(req, res) {
res.sseSetup()
for (var i = 0; i < 5; i++) {
res.sseSend({count: i})
}
})
and when the user uploads a file from the server I just make a call to this route and register all the necessary events with this function on the client side:
progress : () => {
if (!!window.EventSource) {
const source = new EventSource('/stream')
source.addEventListener('message', function(e) {
let data = JSON.parse(e.data)
console.log(e);
}, false)
source.addEventListener('open', function(e) {
console.log("Connected to /stream");
}, false)
source.addEventListener('error', function(e) {
if (e.target.readyState == EventSource.CLOSED) {
console.log("Disconnected from /stream");
} else if (e.target.readyState == EventSource.CONNECTING) {
console.log('Connecting to /stream');
}
}, false)
} else {
console.log("Your browser doesn't support SSE")
}
}
this works as expected, when I upload a track, i get a stream of events counting from 0-4. So thats great!
My Problem/Question: How do i send relevant messages from the audio.process route, to the /stream route so that the messages can be related to whats happening. audio.process has to be a POST, and /stream has to be a GET with the header 'Content-Type': 'text/event-stream'. It seems kind of weird to make GET requests from within audio.process but is this the best way?
Any and all advice/tips are appreciated! Let me know if you need any more info.
New Answer:
Just use socket.io, it's so much easier and better!
https://www.npmjs.com/package/socket.io#in-conjunction-with-express
basic setup:
const express = require('express');
const PORT = process.env.PORT || 5000;
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
// listen to socket connections
io.on('connection', function(socket){
// get that socket and listen to events
socket.on('chat message', function(msg){
// emit data from the server
io.emit('chat message', msg);
});
});
// Tip: add the `io` reference to the request object through a middleware like so:
app.use(function(request, response, next){
request.io = io;
next();
});
server.listen(PORT);
console.log(`Listening on port ${PORT}...`);
and in any route handler, you can use socket.io:
app.post('/post/:post_id/like/:user_id', function likePost(request, response) {
//...
request.io.emit('action', 'user liked your post');
})
client side:
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(e){
e.preventDefault(); // prevents page reloading
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
</script>
full example: https://socket.io/get-started/chat/
Original Answer
Someone (user: https://stackoverflow.com/users/451634/benny-neugebauer | from this article: addEventListener on custom object) literally gave me a hint on how to implement this without any other package except express! I have it working!
First, import Node's EventEmitter:
const EventEmitter = require('events');
Then create an instance:
const Stream = new EventEmitter();
Then create a GET route for event streaming:
app.get('/stream', function(request, response){
response.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
Stream.on("push", function(event, data) {
response.write("event: " + String(event) + "\n" + "data: " + JSON.stringify(data) + "\n\n");
});
});
In this GET route, you are writing back that the request is 200 OK, content-type is text/event-stream, no cache, and to keep-alive.
You are also going to call the .on method of your EventEmitter instance, which takes 2 parameters: a string of the event to listen for and a function to handle that event(that function can take as much params as it is given)
Now.... all you have to do to send a server event is to call the .emit method of your EventEmitter instance:
Stream.emit("push", "test", { msg: "admit one" });
The first parameter is a string of the event you want to trigger (make sure that it is the same as the one in the GET route). Every subsequent parameter to the .emit method will be passed to the listener's callback!
That is it!
Since your instance was defined in a scope above your route definitions, you can call the .emit method from any other route:
app.get('/', function(request, response){
Stream.emit("push", "test", { msg: "admit one" });
response.render("welcome.html", {});
});
Thanks to how JavaScript scoping works, you can even pass that EventEmitter instance around to other function, even from other modules:
const someModule = require('./someModule');
app.get('/', function(request, response){
someModule.someMethod(request, Stream)
.then(obj => { return response.json({}) });
});
In someModule:
function someMethod(request, Stream) {
return new Promise((resolve, reject) => {
Stream.emit("push", "test", { data: 'some data' });
return resolve();
})
}
That easy! No other package needed!
Here is a link to Node's EventEmitter Class: https://nodejs.org/api/events.html#events_class_eventemitter
My example:
const EventEmitter = require('events');
const express = require('express');
const app = express();
const Stream = new EventEmitter(); // my event emitter instance
app.get('/stream', function(request, response){
response.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
Stream.on("push", function(event, data) {
response.write("event: " + String(event) + "\n" + "data: " + JSON.stringify(data) + "\n\n");
});
});
setInterval(function(){
Stream.emit("push", "test", { msg: "admit one" });
}, 10000)
UPDATE:
i created a module/file that is easier to use and doesn't cause memory leaks!
const Stream = function() {
var self = this;
// object literal of connections; IP addresses as the key
self.connections = {};
self.enable = function() {
return function(req, res, next) {
res.sseSetup = function() {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
})
}
res.sseSend = function(id, event, data) {
var stream = "id: " + String(id) + "\n" +
"event: " + String(event) + "\n" +
"data: " + JSON.stringify(data) +
"\n\n";
// console.log(id, event, data, stream);
res.write(stream);
}
next()
}
}
self.add = function(request, response) {
response.sseSetup();
var ip = String(request.ip);
self.connections[ip] = response;
}.bind(self);
self.push_sse = function(id, type, obj) {
Object.keys(self.connections).forEach(function(key){
self.connections[key].sseSend(id, type, obj);
});
}.bind(self);
}
/*
Usage:
---
const express = require('express');
const Stream = require('./express-eventstream');
const app = express();
const stream = new Stream();
app.use(stream.enable());
app.get('/stream', function(request, response) {
stream.add(request, response);
stream.push_sse(1, "opened", { msg: 'connection opened!' });
});
app.get('/test_route', function(request, response){
stream.push_sse(2, "new_event", { event: true });
return response.json({ msg: 'admit one' });
});
*/
module.exports = Stream;
Script located here - https://github.com/ryanwaite28/script-store/blob/master/js/express-eventstream.js

Nodejs - Send data with ajax to server

I try send the values to my server, but If I try, my console show me the error:
Cannot POST /
I try see other examples, and I try with this codes:
My index.html:
function sendData() {
var latestResponse = Api.getResponsePayload();
var context = latestResponse.context;
var mail = context.email; // I can see the data of these variables perfectly on the console
$.ajax({
type: "POST",
url: "http://localhost:3000/",
crossDomain:true,
dataType: "json",
data:JSON.stringify({email: mail})
}).done(function ( data ) {
alert("ajax callback response:"+JSON.stringify(data));
})
}
My server.js:
'use strict';
var server = require('./app');
var port = process.env.PORT || process.env.VCAP_APP_PORT || 3000;
server.on('request', request);
server.listen(port, function() {
console.log('Server on port: %d', port);
});
function request(request, response) {
var store = '';
request.on('data', function(data)
{
store += data;
});
request.on('end', function()
{ console.log(store);
response.setHeader("Content-Type", "text/json");
response.setHeader("Access-Control-Allow-Origin", "*");
response.end(store)
});
}
My repository:
FolderRepository
public
- js folder
- img folder
- css folder
- index.ejs
server.js
app.js
Because your server is running on the other port. This is your port
var port = process.env.PORT || process.env.VCAP_APP_PORT || 3000;
and in ajax request you need to post to the url http://localhost: + your port
And also every time when you receive a request, your request will attach a new event handler to the data event, so after 10 attached events you will get an warning message about the leaking of the memory.
This code works. The main difference is that I call http.createServer() and you get it from the app.js. Look into the app.js and see if the server is created appropriatly.
Try to see if your server is created correctly.
var http = require('http');
var port = 3000;
var proxy = http.createServer();
proxy.listen(port);
proxy.on('request', request);
function request(request, response) {
var store = '';
request.on('data', function (data) {
store += data;
});
request.on('end', function () {
console.log(store);
response.setHeader("Content-Type", "text/json");
response.setHeader("Access-Control-Allow-Origin", "*");
response.end(store)
});
}

Twitch stream status is showing online. while user is offline

I have written a bot in NODE JS which will continuously monitor the twitch users and when some user will get online, then it will send message to "group me" app that user is online.
It is working fine. My problem is that sometimes it send message that user is online but actually user is offline.
Any idea on how to solve this?
See screenshot
var users = ["Statelinejay", "Ad_914", "Houssam06" ];
var messages = ["notsent", "notsent", "notsent" ];
var Client = require('node-rest-client').Client;
var client = new Client();
var express = require('express');
var request = require('request');
var app = express();
app.set('port', (process.env.PORT || 5000));
function theCall(index) {
console.log('Processing ' + users[index]);
client.get('https://api.twitch.tv/kraken/streams/' + users[index] + '?client_id=xxxxxxxxxxxxxxxxxxxxxxx', function (data, response) {
if (data["stream"] === null) {
messages[index] = 'notsent';
console.log(users[index] + 'is offline');
} else
//// Start of sending message
var myJSONObject = {
"bot_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"text": " https://www.twitch.tv/" + users[index]
};
if (messages[index] === 'notsent') {
request.post({
url: " https://api.groupme.com/v3/bots/post",
method: "POST",
json: true, // <--Very important!!!
body: myJSONObject
},
function (error, response, body) {
console.log(error);
}
);
messages[index] = 'sent';
console.log('message sent');
}
//// End of sending message
console.log(users[index] + ' is online') ;
}
theCall((++index % users.length));
});
}
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
theCall(0);
});
Are you sure that data["stream"] is always null whenever the streamer is offline? Can it be undefined? Can you please try
if (!data["stream"])
instead of
if (data["stream"] === null)
?
If this doesn't work, can you console.log your data and response variables for the false online streamer, and update the question?

Nodejs and socket.io to send json changes

I've successfully used nodejs and socket.io to send a large json file from a server to a client, but I'm stumped on the next step: I need to analyse the json, and only send changes to the client, so that I have very fast real-time updates on the client-side, without having to send the entire json every second. I fear I'm missing something really basic. It's currently sending the entire json over and over. I see where that's happening, I just don't see how to send, instead, only the CHANGES. Ideas?
Server:
/*************************** Require modules ********************************/
var app = require('express')()
, request = require('request')
, fs = require('fs')
, http = require('http')
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
/************************* Start socket server ******************************/
server.listen(8127);
// socket.io
io.sockets.on('connection', function(socket){
var options = {
host: 'host.com',
port: 80,
path: '/api/tomyjson.json',
headers: {
'Authorization': 'Basic ' + new Buffer('username' + ':' + 'password').toString('base64')
}
};
function getStreams() {
http.get(options, function(response){
var data = "";
response.on('data', function(chunk) {
data += chunk;
});
response.on('end', function() {
socket.emit('news', JSON.parse(data));
});
});
}
setInterval(getStreams, 5000);
socket.on('message', function(data){
console.log(data)
})
socket.on('disconnect', function(){
})
});
Client JS:
var socket = io.connect('host.com:8127/');
socket.on('news', function (json) {
$.each(json.data, function(i, x) {
console.log(x.json.element);
$('#stream-container').prepend(x.json.element);
})
socket.emit('my other event', { my: 'data' });
});
socket.on('message', function(data){
// Do some stuff when you get a message
oldData += data;
document.getElementById('stream-container').innerHTML = oldData;
});
socket.on('disconnect', function(){
// Do some stuff when disconnected
});

Categories

Resources