Call NodeJS function by PHP (fsocketopen)
I need call and pass parameter to NodeJS socket server.
I confirmed the server works well. and now I need to create PHP script to call the 开发者_StackOverflow中文版function.
My NodeJS code is like this,
var user = {};
socket.sockets.on("connection", function(client){
client.on("messageToClient", function(uid, msg){ // I need to call this method
user[uid].send(msg);
});
});
PHP ::
$fp = fsockopen("10.0.111.10","3000",$errno,$errstr, 30);
if(!$fp){
echo "{$errno} ({$errstr}) <br />";
}else{
$uid_parameter = 'ABC';
$msg_parameter = 'HELLO';
$out = "HOW TO CALL NodeJS messageToClient Method AND PASS PARAMETER?";
fwrite($fp,$out);
fclose($fp);
}
The more elegant solution would be just do it all in Nodejs or all in PHP. DB interaction as well. NodeJS can interact with almost every type of commonly used database. It would save you having to implement what will be a quite hacky code.
I know this question is old, but hasn't content on the internet, so I will leave the answer here for future users.
PHP:
function sio_message($message, $data) {
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$result = socket_connect($socket, '127.0.0.1', 9501);
if(!$result) {
die('cannot connect '.socket_strerror(socket_last_error()).PHP_EOL);
}
$bytes = socket_write($socket, json_encode(Array("msg" => $message, "data" =>
$data)));
socket_close($socket);
}
NODE.JS:
var express = require('express');
var app = require('express')();
var server = require('http').Server(app);
server.on("connection", function(s) {
//If connection is from our server (localhost)
if(s.remoteAddress == "::ffff:127.0.0.1") {
s.on('data', function(buf) {
console.log('data arrive');
var js = JSON.parse(buf);
console.log(js.data); //Done
});
}
});
Now you can send data from node with only sio_message('anything', 'more data');
精彩评论