Error using node request library on socket io - javascript

I'm using socket io on my laravel project and I have a problem with the request on my disconnect event in the socket.js file.
I have debugged my code and the error is with the request library.
Socket.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(5000);
io.on('connection', function (socket) {
console.log("new client connected " + socket.id);
socket.on('disconnect', function() {
var socket_id = socket.id;
console.log('client disconnected :C '+socket_id);
var request = require('request');
var url_request = 'http://example.com/play-session/close?socket_id=' + socket_id;
request(url_request, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('session closed '+socket_id);
}
});
});
});
Error:
SyntaxError: Error parsing /var/www/example.com/public_html/node_modules/aws4/package.json: Unexpected token <
at Object.parse (native)
at readPackage (module.js:113:52)
at tryPackage (module.js:123:13)
at Function.Module._findPath (module.js:190:18)
at Function.Module._resolveFilename (module.js:336:25)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/var/www/example.com/public_html/node_modules/request/request.js:11:12)
at Module._compile (module.js:456:26)
I don't know what is happening. I appreciate all the help, thanks.
Updated, Fix issue complete:
I fix this issue with this: https://www.npmjs.com/package/request#unix-domain-sockets, ussing that example like this:
Socket.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
var request = require('request');
server.listen(5000);
io.on('connection', function (socket) {
console.log("new client connected " + socket.id);
socket.on('disconnect', function() {
var socket_id = socket.id;
console.log('client disconnected :C '+socket_id);
var url_request = 'http://example.com/play-session/close?socket_id='+socket_id;
request.get(url_request); // this line fix it
});
});
Thanks to all for your help.

You can fix this issue with this: https://www.npmjs.com/package/request#unix-domain-sockets, ussing that example like this:
request.get(url_request);
Regards

Related

JS + Socket.io + Heroku Problems - Socket.id problem

Solution
Change
var server = app.listen(3000);
To
var server = app.listen(process.env.PORT || 5000);
I want to deploy an game made with JavaScript on Heroku.
Here's my server:
var express = require('express');
var app = express();
var server = app.listen(3000);
var socket = require('socket.io');
var io = socket(server);
app.use(express.static('public'));
var connectedPlayers = {};
console.log("Server is running!");
io.on('connection',
function (socket) {
socket.on('newPlayer',
function (data) {
console.log("New player connected - ID: " + data.id);
connectedPlayers[socket.id] = {
idOnline: socket.id,
idOffline: data.id,
x: data.w,
y: data.h
};
socket.emit('allPlayers', connectedPlayers);
socket.broadcast.emit('newPlayer', connectedPlayers[socket.id]);
});
socket.on('move',
function (data) {
connectedPlayers[socket.id].x = data.x;
connectedPlayers[socket.id].y = data.y;
socket.broadcast.emit('move', connectedPlayers[socket.id]);
});
socket.on('message',
function (data) {
message = {
name: data.name,
message: data.message,
messageId: generateId()
};
socket.broadcast.emit('message', message);
});
socket.on('emote',
function (data) {
message = {
emote: data.emote,
id: socket.id
}
socket.broadcast.emit('emote', message);
});
socket.on('disconnect', function () {
delete connectedPlayers[socket.id];
io.emit('remove', socket.id);
});
});
This work's fine locally, but when I deploy to heroku I get this error message:
2018-11-23T21:04:18.009491+00:00 app[web.1]: /app/server.js:33
2018-11-23T21:04:18.009512+00:00 app[web.1]: connectedPlayers[socket.id].x = data.x;
2018-11-23T21:04:18.009514+00:00 app[web.1]: ^
2018-11-23T21:04:18.009516+00:00 app[web.1]:
2018-11-23T21:04:18.009518+00:00 app[web.1]: TypeError: Cannot set property 'x' of undefined
I understand that heroku is not recognizing the "connectedPlayers" array at that index, but how this can work properly locally?
What's wrong with the socket.id property?
PS.: the socket.id it's sended by the client, but I think that's generated after a client establish an connection with the server right?
After looking for a lot of solutions, I was trying crazy things to insert the:
process.env.PORT || 5000
on the server.listen.
As you can see in the code of the question, I've posted an out of date code, with the following line (my first try):
var server = app.listen(3000);
The solution was simplier than I thought, just changing the above line of code to:
var server = app.listen(process.env.PORT || 5000);

Node.js Server crashed when Refresh Browser

I tried to build a chat box server by node.js. When the browser requestes the page, it workes well at first. But when I refresh the page, the Server crashes.
Below is the error message:
events.js:183
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at _errnoException (util.js:1022:11)
at TCP.onread (net.js:615:25)
I used the node --inspect index.js, but could not find the point.
Below is the code of index.js:
const http = require('http');
const fs = require('fs');
const extract = require('./extract');
const wss = require('./websockets-server');
var handleError = function (err,res) {
res.writeHead(404);
res.end();
}
var server = http.createServer(function (req, res) {
console.log("Responding to a request.");
var filePath = extract(req.url);
console.log("filePath:"+filePath);
fs.readFile(filePath,function (err,data) {
if(err){
handleError(err,res);
return;
}else {
res.end(data);
}
})
})
server.listen(3000);
When I comment the 4th line, the import of websockets-server. Server works well when I refresh the page. Maybe it's about the websocket while it works without websocket.
Below is code of websockets-server.js:
const WebSocket = require('ws');
var WebSocketServer = WebSocket.Server;
var port = 3001;
var ws = new WebSocketServer({
port:port
});
var message = [];
console.log('websockets server started');
ws.on('connection', function (socket) {
console.log('client connection established');
message.forEach(function (msg) {
socket.send(msg);
})
socket.on('message', function (data) {
console.log('message received: ' + data);
message.push(data);
ws.clients.forEach(function (clientSocket) {
clientSocket.send(data);
});
});
});
Does the problem is about the websocket? Whether should I do process when the client shutdown the connection with the server while refreshing the page.
extract.js below:
const path = require('path');
var extractFilePath = function (url) {
var filePath;
var fileName = 'index.html';
if(url.length > 1){
fileName = url.substring(1);
}
console.log('The fileName is: ' + fileName);
filePath = path.resolve(__dirname, 'app', fileName);
return filePath;
}
module.exports = extractFilePath;
I guess that you maybe execute var ws = new WebSocket("ws://localhost:3001"); in html file. I haven't figured out exact reason about your error as I'm not proficient in WebSocket. But there is a solution:
window.onbeforeunload = function () {
ws.close();
}
close connection before reload, then the error will not reappear.
You need to add an error listener on the socket. Error listener only on the websocket instance does not help in this case.
socket.on('error', function(e){
console.log(e);
});
The ECONNRESET error means that the other side (browser) closed the connection abruptly. On browser refresh, browser simple killed the connection with the websocket server.
To solve this, you have to listen for the error event on the websocket server instance.
// listen for "error" event so that the whole app doesn't crash
wss.on("error", function(error){
console.log(error);
}
I was having the same problem, but it resolved after this command:
npm install #ionic/app-scripts#nightly --save-dev

SyntaxError: Unexpected token >

I just installed node and tried to write and run some programs.
When I tried this example progra, I get an error.
Maybe node and npm were installed incorrectly?
Maybe some necessary packages should be install?
const http = require('http');
const net = require('net');
const url = require('url');
// Create an HTTP tunneling proxy
var proxy = http.createServer( (req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('okay');
});
proxy.on('connect', (req, cltSocket, head) => {
// connect to an origin server
var srvUrl = url.parse(`http://${req.url}`);
var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => {
cltSocket.write('HTTP/1.1 200 Connection Established\r\n' + 'Proxy-agent: Node.js-Proxy\r\n' + '\r\n');
srvSocket.write(head);
srvSocket.pipe(cltSocket);
cltSocket.pipe(srvSocket);
});
});
Why does the below error appear?
var proxy = http.createServer( (req, res) => {
^
SyntaxError: Unexpected token >
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3 ##
Try it like this;
var requestListener = function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('okay');
}
var proxy = http.createServer(requestListener);

ECONNREFUSED when starting node express application

events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:4562
at Object.exports._errnoException (util.js:837:11)
at exports._exceptionWithHostPort (util.js:860:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1060:14)
here is my code
var express = require('express');
var net = require('net');
var app = express();
var i = 0;
app.get('/', function (req, res)
{
i = i+1; //no of clinets request gin ne ki liye
console.log(i + "fa..sa");
var client = net.connect({port: 4562},"192.168.202.101", function() {
console.log('connected to server!'); });
client.write("Ho gaya bhai");
client.end();
res.send('ho gaya bhai..');
});
app.listen(6544);
As you can see from your error message you have an error in the way you call net.connect. It looks like you want to connect to 192.168.202.101:4562, but you try to connect to ´127.0.0.1:4562´. Try either:
net.connect({ port: 4562, host: "192.168.202.101"}, function(){});
or:
net.connect(4562, "192.168.202.101", function() {});

Can't get plotly + node.js to stream data coming through POST requests

I'm trying to get plotly to stream data received by my server through a POST request to http://localhost:3000/step.
Building on the rest-example.js in plotly-nodejs/examples, here's my server code (I've blurred out my username, apikey, and token):
'use strict';
var express = require('express');
var logger = require('morgan');
var bodyParser = require('body-parser');
var events = require('events');
var eventEmitter = new events.EventEmitter();
var app = express();
var server = require('http').Server(app);
var port = process.env.PORT || 3000;
server.listen(port);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/step', function(req, res) {
var data = req.body.data;
eventEmitter.emit('step', data);
res.end('ok');
});
var plotly = require('plotly')('username', 'apikey');
var token = 'token';
var dataInit = [{x:[], y:[], stream: { token: token, maxpoints: 10 } }];
var layout = {fileopt : "extend", filename : "REST-test"};
plotly.plot(dataInit, layout, function (err, msg) {
if(err) return console.error('step data error', err.stack);
var stream = plotly.stream(token, function() {});
eventEmitter.on('step', function(data) {
console.log('sending to plotly: ' + data + ' steps');
var streamObject = JSON.stringify({ x: getDateString(), y: data });
stream.write(streamObject+'\n');
});
});
function getDateString() {
var d = new Date();
return d.toLocaleString();
};
When I POST data using cURL, for example curl http://localhost:3000/step --data "data=5", I can see that the data reaches the callback inside the plotly.plot block, but plotly never starts up and streams the data.
In some slightly more complex server code I was working on earlier, I also get the error which may or may not be related and which always points to the beginning of the plotly.plot block.
cb(null, body);
^
SyntaxError: Unexpected end of input
This is the full error stack:
/home/plotly-testing/node_modules/plotly/index.js:305
cb(null, body);
^
SyntaxError: Unexpected end of input
at Object.parse (native)
at /home/plotly-testing/node_modules/plotly/index.js:72:25
at IncomingMessage.<anonymous> (/home/plotly-testing/node_modules/plotly/index.js:305:9)
at IncomingMessage.emit (events.js:129:20)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
---------------------------------------------
at IncomingMessage.Readable.on (_stream_readable.js:671:33)
at parseRes (/home/plotly-testing/node_modules/plotly/index.js:304:9)
at ClientRequest.<anonymous> (/home/plotly-testing/node_modules/plotly/index.js:71:9)
at ClientRequest.emit (events.js:107:17)
at HTTPParser.parserOnIncomingClient (_http_client.js:426:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:111:23)
at TLSSocket.socketOnData (_http_client.js:317:20)
---------------------------------------------
at new ClientRequest (_http_client.js:93:10)
at Object.exports.request (http.js:49:10)
at Object.exports.request (https.js:136:15)
at Plotly.plot (/home/plotly-testing/node_modules/plotly/index.js:70:21)
at Object.<anonymous> (/home/plotly-testing/index.js:175:8)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
Line 305 of plotly/index.js points to the following method, which seems to indicate something was wrong in one of my callbacks, but I'm not sure.
// response parse helper fn
function parseRes (res, cb) {
var body = '';
if ('setEncoding' in res) res.setEncoding('utf-8');
res.on('data', function (data) {
body += data;
if (body.length > 1e10) {
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQ
res.connection.destroy();
res.writeHead(413, {'Content-Type': 'text/plain'});
res.end('req body too large');
return cb(new Error('body overflow'));
}
});
res.on('end', function () {
cb(null, body);
});
}
So I've modified the code to include a console.log inside the Plotly.plot callback.
See gist here:
https://gist.github.com/alexander-daniel/b36f9be78abbbaa4847e#file-index-js-L33
And that way we can see that Plotly returned a graph URL that we can look at.
https://gist.github.com/alexander-daniel/b36f9be78abbbaa4847e#file-console_output-L5
That should resolve the first issue.
As far as the second issue goes, it seems the problem is two fold:
- JSON.parse calls inside the library are not wrapped in try/catch, so it looks like if the stream-server returns anything that is not JSON, this will break.
We're looking into the streaming-server error returns, but I have opened this issue here re: the try/catch blocks in the API library.
github.com/plotly/plotly-nodejs/issues/37

Categories

Resources