Error: Cannot send request to server. node php-fpm localhost - php

fpm library. I want to integrate pubnub and replace socket io with it, but my code does not work in localhost.
What i have done till now
i have followed this to install fpm in xampp. Did i miss something? what i can do to run it?
after installing it worked for once but again stopped working (did not change anything in code).
the code works fine on live server.but in localhost i am getting below error.
Stripped content to Error: Cannot send request to server. but found something wrong...
see below image
This is my code
"use strict";
var PHPFPM = require('node-phpfpm');
var striptags = require('striptags');
const log = require('simple-node-logger').createSimpleFileLogger(process.env.LOGDIR + '/poker-phpwrapper.log');
class PHPWrapper {
constructor(concierge) {
this.phpfpm = new PHPFPM({
host: process.env.NODE_POKER_PHP_HOST,
post: process.env.NODE_POKER_PHP_PORT,
documentRoot: process.env.NODE_POKER_PHP_DOCROOT
});
this.concierge = concierge;
this.busy = false;
}
houseKeeping(messages) {
var php = this;
php.busy = true;
this.phpfpm.run({
uri: 'server_wrapper.php',
json: {
func: "houseKeeping",
messages: messages
}
}, function (err, body, phpErrors) {
php.busy = false;
if (body.trim() == '') {
return;
}
// Check for PHP errors
if (body.includes('<br />')) {
// Get all the errors out until we've just got JSON left
body = body.substring(body.indexOf('\n[')+1);
}
if (body.charAt(0) != '[') {
console.log('Stripped content to ' + body + " but found something wrong...");
}
try {
var data = JSON.parse(body);
} catch (parseError) {
// throw("An error occurred parsing the JSON from PHP: " + parseError + "\nBody contents:\n" + body);
data = '';
}
if (data.length == 0) {
return;
}
for (var i in data) {
if (data[i][0] == 'CONTROL') {
// Server control message, execute as appropriate
switch (data[i][1]) {
case 'force_exit': php.concierge.wipeStateAndExit(); break;
case 'reset_server': php.concierge.wipeState(); break;
}
} else {
// Message for client
php.concierge.msgToClient(data[i][0], data[i][1]);
}
}
});
}
isBusy() {
return this.busy;
}
}
module.exports = PHPWrapper;

Related

How do I do WebRTC signaling using AJAX and PHP?

I'm new to WebRTC and I don't understand how the signaling works on the server side. I know the request must be two-way. I'm able to send an offer to a PHP page but from there I'm stuck.. How does the other peer pick that offer so that it can generate an answer? I don't want a socket solution because I don't have my own server and I don't want to have a third-party dependency.
I have created an offer and sent that offer to a PHP page. See my code:
var myPeerConnection;
var caller_video=document.getElementById('caller_video');
var receiver_video=document.getElementById('receiver_video');
var mediaConstraints = {
video:true,
audio:false
};
function sendToServer(msg){
var msgJSON = JSON.stringify(msg);
$.ajax({
type:'get',
url:'offer.php',
data:'object='+msgJSON,
beforeSend:function(){
console.log('Sending...');
},
success:function(data){
console.log(data);
}
});
}
function reportError(error){
console.log(error.name);
}
function handleNegotiationNeededEvent(){
myPeerConnection.createOffer().then(function(offer) {
return myPeerConnection.setLocalDescription(offer);
})
.then(function(){ // so here I'm supposed to send an offer
sendToServer({
name: myUsername,
target: targetUsername,
type: "video-offer",
sdp: myPeerConnection.localDescription
});
})
.catch(reportError);
}
function handleICECandidateEvent(event){
if(event.candidate){//send the ICECandidates
sendToServer({
name: myUsername,
target: targetUsername,
type: "new-ice-candidate",
candidate: event.candidate
});
}
}
function handleTrackEvent(event){
console.log(event);
document.getElementById("received_video").srcObject = event.streams[0];
}
function handleRemoveTrackEvent(event){
var stream = document.getElementById("received_video").srcObject;
var trackList = stream.getTracks();
if (trackList.length == 0){
closeVideoCall();
}
}
function handleICEConnectionStateChangeEvent(event){
console.log('ICE connection changed!');
switch(myPeerConnection.iceConnectionState) {
case "closed":
case "failed":
case "disconnected":
closeVideoCall();
break;
}
}
function handleICEGatheringStateChangeEvent(event){
console.log('Is gathering');
console.log(event);
}
function handleSignalingStateChangeEvent(event) {
console.log('Signaling state changed');
switch(myPeerConnection.signalingState) {
case "closed":
closeVideoCall();
break;
}
};
function createPeerConnection() {
var STUN = {
'url': 'stun:stun.l.google.com:19302',
};
var iceServers =
{
iceServers: [STUN]
};
myPeerConnection = new RTCPeerConnection(iceServers);
myPeerConnection.onnegotiationneeded = handleNegotiationNeededEvent;
myPeerConnection.onicecandidate = handleICECandidateEvent;
myPeerConnection.ontrack = handleTrackEvent;
myPeerConnection.onremovetrack = handleRemoveTrackEvent;
myPeerConnection.oniceconnectionstatechange = handleICEConnectionStateChangeEvent;
myPeerConnection.onicegatheringstatechange = handleICEGatheringStateChangeEvent;
myPeerConnection.onsignalingstatechange = handleSignalingStateChangeEvent;
}
function handleGetUserMediaError(e) {
switch(e.name) {
case "NotFoundError":
alert("Unable to open your call because no camera and/or microphone" +
"were found.");
break;
case "SecurityError":
case "PermissionDeniedError":
// Do nothing; this is the same as the user canceling the call.
break;
default:
alert("Error opening your camera and/or microphone: " + e.message);
break;
}
closeVideoCall();
}
function closeVideoCall(){
//do something to exit the video call
}
//invite the other peer...we want to send our SDP
function invite(evt){
if (myPeerConnection){
console.log('Call already started');
}
else{
//myPeerConnection=new MediaStream();
targetUsername ='Nevil';//Unique other peer username
myUsername='Philip';
createPeerConnection();//this function creates a peer connection//uses the STUN/TURNS servers...updates myPeerConnection variable so it's not null
navigator.mediaDevices.getUserMedia(mediaConstraints)//grab our media constraints
.then(function(localStream) {
caller_video.srcObject =localStream;
caller_video.play();
localStream.getTracks().forEach(track => myPeerConnection.addTrack(track, localStream));
})
.catch(handleGetUserMediaError);
}
}
//we click the call button
document.querySelector('#callBt').addEventListener('click',function(){
invite();
});
I know there must be a way to send back the answer but I would like to just send the offer; that way I will understand how both peers exchange the SDP on the backend. Please try using PHP. If anyone can create a signaling XHR request, I will appreciate it.

verifyIdToken works one time and fails another time

I'm trying to implement google sign-in to on my website.
I've done the steps from here Authenticate with Google.
This function executes after i have logged in to google :
function onSignIn(googleUser) {
var googleResponse = googleUser.getAuthResponse();
google_login(googleResponse, true);
};
Google_login function:
function google_login(res) {
var httpObject = getXMLHTTPObject();
var ajax_url = siteURL + 'google_login';
var params = 'token='+encodeURIComponent(res.id_token);
httpObject.open('POST', ajax_url, true);
httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpObject.onreadystatechange = function() {
if (httpObject.readyState == 4) {
if(httpObject.responseText == 'true') {
window.location = httpObject.responseURL;
}
else {
if(httpObject.responseText == '') {
window.location = siteURL + 'login_again';
}
else {
window.location = siteURL + 'google_login_error';
}
}
}
};
httpObject.send(params);
}
And in my model I'm using this code:
private $google_client;
function Google_model() {
parent::__construct();
$this->google_client = new Google_Client(['client_id' => 'my_client_id','client_secret' =>'my_client_secret']);
}
function check_google_user($access_token) {
$payload = $this->google_client->verifyIdToken($access_token);
if ($payload) {
return $payload;
}
return false;
}
In my controller I'm calling check_google_user function.
And here appears a strange behaviour. Sometimes when I try to login I get the payload, and sometimes not (PS: I'm trying to login with the same user in the same day). Am I doing something wrong?
EDIT:
I'm getting this error: Caught exception: Cannot handle token prior to 2017-01-25T16:20:24+0200
Solved this by commenting these lines in firebase JWT.php file:
throw new BeforeValidException(
'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
);

need to run long taking task in php

In a commercial project I need to periodically monitor SMTP and Accounting servers to see if its running and working properly.
if its dead update a table in mysql.
I cant install any 3rd party app on server hosting php script or use exec or modify php settings through php_ini_set
each task takes about 10 to 30 seconds
I tried to run tasks through Jquery ajax calls
and it worked , but the problem is when the jquery request is running you cant navigate to any other page and xhr.abort(); is not working , and stucks on loading until jquery task finishes.
This is what i tried in my js file
var monitor_running = false;
var xhr;
function monitor() {
if (document.readyState === "complete") {
if (monitor_running === false) {
monitor_call();
}
else {
console.log("jobs Already running ===>");
}
}
}
window.onbeforeunload = function () {
console.log(xhr);
xhr.abort();
alert(xhr.status);
};
setInterval(monitor, monitor_interval * 1000);
function monitor_call() {
monitor_running = true;
console.log("jobs running");
xhr = $.ajax({url: './ajax.php',
data: {
cmd: 'monitor'
},
type: 'post',
async: true,
success: function (output) {
monitor_running = false;
console.log(output + " job is finished");
}
});
}
and in php page :
<?php
include_once '../includes/config.php';
$tpl_obj = new template('admin');
$navigation_obj = new navigation();
$auth = $navigation_obj->admin_is_auth();
if (!$auth) {
die('Auth Failed !');
}
function monitor() {
sleep(10);
echo 'done';
// $monReport['acc'] = monitor::domon('acc');
// $monReport['smtp'] = monitor::domon('smtp');
// $monReport['payment'] = monitor::domon('payment');
// $monReport['dns'] = monitor::domon('dns');
// return json_encode($monReport);
}
$cmd_post = filter_input(INPUT_POST, 'cmd');
$cmd_get = filter_input(INPUT_GET, 'cmd');
if ($cmd_post == 'monitor') {
echo monitor();
}

How to response to all clients with websocket?

I'm working on a small project with PHP-Websocket.
The Server side is running with this https://github.com/ghedipunk/PHP-Websockets
Server side:
require "PHP-Websockets/websockets.php";
class Server extends WebSocketServer
{
private $_connecting = 'Connecting..';
private $_welcome = 'SOCKET SERVER!';
protected function connected($user)
{
// Send welcome message to user when connected
}
protected function process($user, $message)
{
// data sent from client
$json = json_decode($message);
//prepare data response to client
$response = json_encode(array('type'=>'notify', 'message'=>'Client'.$user->id.' has sent a request.'));
$this->send($user, $response);
}
protected function closed($user)
{
// Alert on server
echo "User $user->id has closed the connection".PHP_EOL;
}
public function __destruct()
{
echo "Server Closed!".PHP_EOL;
}
}
$addr = 'localhost';
$port = '2207';
$server = new Server($addr, $port);
$server->run();
Client Side:
<script>
var uri = "ws://localhost:2207";
function socket_connect(){
socket = new WebSocket(uri);
if(!socket || socket == undefined) return false;
socket.onopen = function(){
console.log('Connected to Server!');
}
socket.onerror = function(){
console.log('Connection Failed!');
}
socket.onclose = function(){
socket_log('Connection Closed! ')
}
socket.onmessage = function(e){
//var response_data = e.data;
var msg = JSON.parse(e.data); //PHP sends Json data to client
console.log(msg.message);
var new_response = '<li>'+msg.message+'</li>;
$('#response').append(new_response);
}
}
function send_data_to_server(data){
if(!socket || socket == undefined) return false;
socket.send(JSON.stringify(data));
}
$(document).ready(function(){
socket_connect();
$('#send_request').click(function(){
send_data_to_server({message: 'Message sent from Client'});
});
});
</script>
<input type="button" id="send_request" value="Send Request to Server" />
<ul id="responses"></ul>
Everything works fine with those code above.
When Client1 sends a request to Server, the Server responses to him instantly. BUT the other clients can not see the response message.
So I want to make it go further : When a client sends a request to the server, the server will response to ALL clients so that all client can see the message.
How can I do that?
Thanks in advance && sorry for my bad English!
When a user connect, you need to add him to an array with every other users.
When one disconnect, remove him from this array.
Then when you want to send a message to every user, iterate on the array and send the message to each connected user.
WebSocketServer class has WebSocketServer::$users variable.
If you iterate over WebSocketServer::$users in split_packet function and then call main process it will work. In latest source code please iterate in line no-405.
//original
if ((preg_match('//u', $message)) || ($headers['opcode']==2)) {
//$this->stdout("Text msg encoded UTF-8 or Binary msg\n".$message);
$this->process($user, $message);
} else {
$this->stderr("not UTF-8\n");
}
//have to change
if ((preg_match('//u', $message)) || ($headers['opcode']==2)) {
//$this->stdout("Text msg encoded UTF-8 or Binary msg\n".$message);
foreach($this->users as $usr){
$this->process($usr, $message);
}
} else {
$this->stderr("not UTF-8\n");
}

Node.js server sends back EOF block the PHP server

I have a node.js server opening 8000 port. It is a chat server.
I have another PHP server and I use proxy + virtual host so when I go www.phpserver.com/chat It proxies to the node.js server. I did this so I can use ajax to call the node.js server.
Right now, everything works fine when i run the node.js server, however, after a while (a random time frame, not necessarily long or short), the PHP server will crush because it gets an EOF from the node.js server and it's just stuck there until I stop/restart the node.js server.
The error I get is(from php error log):
(70014)End of file found: proxy: error reading status line from remote
server nodeserver.com:8000, referer: https://www.phpserver.com
I asked some professionals and they said it's because of the PHP server sends the request to the node.js server successfully and receives an EOF or fails to receive any response. I don't understand how to fix it tho. What should I do so even the node.js server crushes, it won't crush the PHP server? Should I get rid of the proxy+ajax and starts to use socket.io?
Please advise.
Thank you!
Below is some node codes.
From middleware:
this.events.addListener('update', o_.bind(function(package) {
if(this.clear != 0){
delete this.sessions[this.clear];
}
var _package = package.toJSON();
if(package.type == 'status' && package.status == 'offline') {
var sids = Object.keys(this.sessions), sid, sess;
for(sid in this.sessions) {
sess = this.sessions[sid];
if(sess.data('username') == package.username) {
if(sess.listeners.length)
sess.send(200, {type: 'goodbye'});
delete this.sessions[sid];
break;
}
}
}
}, this));
};
Hub.prototype.destroy = function(sid, fn) {
this.set(sid, null, fn);
};
Hub.prototype.reap = function(ms) {
var threshold = +new Date - ms,
sids = Object.keys(this.sessions);
for(var i = 0, len = sids.length; i < len; ++i) {
var sid = sids[i], sess = this.sessions[sid];
if(sess.lastAccess < threshold) {
this.events.emit('update', new packages.Offline(sess.data('username')));
}
}
};
Hub.prototype.get = function(req, fn) {
if(this.sessions[req.sessionID]) {
fn(null, this.sessions[req.sessionID]);
} else {
this.auth.authenticate(req, o_.bind(function(data) {
if(data) {
var session = new User(req.sessionID, data);
this.set(req.sessionID, session);
this.auth.friends(req, data, o_.bind(function(friends) {
var friends_copy = friends.slice();
o_.values(this.sessions).filter(function(friend) {
return ~friends.indexOf(friend.data('username'));
}).forEach(function(friend) {
var username = friend.data('username');
friends_copy[friends_copy.indexOf(username)] =
[username, friend.status()];
}, this);
session._friends(friends_copy);
console.log("refreshed");
session.events.addListener('status',
o_.bind(function(value, message) {
this.events.emit(
'update',
new packages.Status(session.data('username'),
value,
message)
);
}, this));
this.events.addListener('update',
o_.bind(session.receivedUpdate, session));
this.set(req.sessionID, session);
fn(null, session);
}, this));
} else {
fn();
}
}, this));
}
};
From app.js
#!/usr/bin/env node
var sys = require('sys'),
express = require('express'),
packages = require('./libs/packages'),
fs = require('fs'),
o_ = require('./libs/utils'),
https = require('https');
o_.merge(global, require('./settings'));
try { o_.merge(global, require('./settings.local')); } catch(e) {}
try {
var daemon = require('./libs/daemon/daemon'),
start = function() {
daemon.init({
lock: PID_FILE,
stdin: '/dev/null',
stdout: LOG_FILE,
stderr: LOG_FILE,
umask: 0,
chroot: null,
chdir: '.'
});
},
stop = function() {
process.kill(parseInt(require('fs').readFileSync(PID_FILE)));
};
switch(process.argv[2]) {
case 'stop':
stop();
process.exit(0);
break;
case 'start':
if(process.argv[3])
process.env.EXPRESS_ENV = process.argv[3];
start();
break;
case 'restart':
stop();
start();
process.exit(0);
break;
case 'help':
sys.puts('Usage: node app.js [start|stop|restart]');
process.exit(0);
break;
}
} catch(e) {
sys.puts('Daemon library not found! Please compile ' +
'./libs/daemon/daemon.node if you would like to use it.');
}
var options = {
key: fs.readFileSync('/home/ec2-user/key.pem'),
cert: fs.readFileSync('/home/ec2-user/cert.pem'),
ca: fs.readFileSync('/home/ec2-user/ca.pem'),
};
var app = express();
//app.set('env', 'development');
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(require('./middleware/im')({
maxAge: 30 * 1000,
reapInterval: 20 * 1000,
authentication: require('./libs/authentication/' + AUTH_LIBRARY)
}));
app.set('root', __dirname);
if ('development' == app.get('env')) {
app.set('view engine', 'jade');
app.set('views', __dirname + '/dev/views');
app.stack.unshift({
route: '/dev',
handle: function(req, res, next) {
req.dev = true;
next();
}
});
app.use(express.logger());
require('./dev/app')('/dev', app);
app.use(express.static(
require('path').join(__dirname, '../client')));
app.use(express.errorHandler({dumpExceptions: true, showStack: true}));
}
//app.listen(APP_PORT, APP_HOST);
// Listener endpoint; handled in middleware
app.get('/listen', function(){});
app.post('/message', function(req, res) {
res.find(req.body['to'], function(user) {
if(!user)
return res.send(new packages.Error('not online'));
res.message(user, new packages.Message(
req.session.data('username'),
req.body.body
));
});
});
app.post('/message/typing', function(req, res) {
if(~packages.TYPING_STATES.indexOf('typing' + req.body['state'])) {
res.find(req.body['to'], function(user) {
if(user) {
res.message(user, new packages.Status(
req.session.data('username'),
'typing' + req.body.state
));
}
// Typing updates do not receive confirmations,
// as they are not important enough.
res.send('');
});
} else {
res.send(new packages.Error('invalid state'));
}
});
app.post('/status', function(req, res) {
if(~packages.STATUSES.indexOf(req.body['status'])) {
res.status(req.body.status, req.body.message);
res.send(new packages.Success('status updated'));
} else {
res.send(new packages.Error('invalid status'));
}
});
app.post('/online', function(req, res) {
var d = new Date();
var n = d.getTime() + 30;
req.sessionID.expires = n;
res.status(req.body.status, 'available');
});
app.post('/signoff', function(req, res) {
res.signOff();
res.send(new packages.Success('goodbye'));
});
app.use(function(err, req, res, next){
console.error(err.stack);
res.send(500, 'Error on the node/express server.');
});
https.createServer(options, app).listen(8000);
I can't help you answer your question but I can try to point you in a right direction.
I'm currently working on a Node JS server myself, and I found very useful to have a logger setup.
There are a few of them, but my favorite is Winston so far.
Reference: https://github.com/flatiron/winston
To install Winston for your Node JS server (seems you have already installed a few modules):
npm install winston
Then I have logger module setup as (logger.js):
/**
* Usage:
* - logger.info('sample text');
* - logger.warn('sample text');
* - logger.error('sample text');
*/
// Load modules
var winston = require('winston');
// Create custom logger
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ json: false, timestamp: true }),
new winston.transports.File({ filename: __dirname + '/debug.log', json: false })
],
exceptionHandlers: [
new (winston.transports.Console)({ json: false, timestamp: true }),
new winston.transports.File({ filename: __dirname + '/exceptions.log', json: false })
],
exitOnError: false
});
// Export logger
module.exports = logger;
Finally I load in Winston logger module into my server scripts by:
var logger = require('./logger');
It will automatically log any exceptions into exceptions.log on your Node JS server location. It helped me out a lot to catch exceptions I haven't noticed before within Node JS unrelated to PHP.
P.S. Also check out socket.io, that may simplify what you are trying to do.

Categories