简体   繁体   English

PHP curl向Node.js发送消息没有返回结果

[英]PHP curl sending message to Node.js returns no result

I wanted to implement websockets to a complex web system to synchronize data properly. 我想将websockets实现到复杂的Web系统以正确同步数据。 The idea was that all clients may make ajax-calls, php handles those calls, may edit data on a database and on success the php-backend sends some data to a websocket-server. 这个想法是,所有客户端都可以进行ajax调用,php可以处理这些调用,可以在数据库上编辑数据,并且成功后php后端会将一些数据发送到websocket服务器。 That websocket server then sends the data to all subscribed clients, which may be interested in the data. 然后,该网络套接字服务器将数据发送到所有订阅的客户端,这些客户端可能对数据感兴趣。

So far clients can subscribe to the websocket server (socket.io) but I can't figure out how to make php send messages to the websocket server. 到目前为止,客户端可以订阅websocket服务器(socket.io),但我不知道如何使php将消息发送到websocket服务器。

So far my websocket server looks like this: 到目前为止,我的websocket服务器看起来像这样:

const fs = require('fs');

const credentials = {
  key: fs.readFileSync('C:/xampp/apache/conf/ssl.key/server.key'),
  cert: fs.readFileSync('C:/xampp/apache/conf/ssl.crt/server.crt')
};
const app = require('express')();



// var server = require('https').Server(app);
let server = require('https').createServer(credentials, app);
let io = require('socket.io')(server);

server.listen(3000);

io.sockets.on('connection', function(socket){
    console.log("connected");
    socket.emit('test', { hello: 'world' });
    socket.on('some other event', function (data) {
        console.log(data);
    });

    socket.on('subscribe', function(room) {
        console.log('joining room', room);
        socket.join(room);
    });

    socket.on('unsubscribe', function(room) {
        console.log('leaving room', room);
        socket.leave(room);
    });

    socket.on('send', function(data) {
        console.log('sending message');
        io.sockets.in(data.room).emit('message', data);
    });
});

And my php-calls look like this: 我的php调用看起来像这样:

require_once __DIR__.'/../vendor/autoload.php';
$dbHandler = \services\DBHandling::getInstance();


$data = [
    "subscribe" => "room3",
    "message" => "evacuate nuclear reactor block B !"
];
$data_string = json_encode($data);

$curl = curl_init("http://localhost");

curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,['Content-Type: application/json',
    'Content-Length: ' . strlen($data_string)
]);

curl_setopt($curl,CURLOPT_PORT, 3000);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl,CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,$data_string);

$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($status != 200) {
    print_r([
        'Error',
        $status,
        curl_errno($curl)
    ]);
}
curl_close($curl);

The php-backend only needs to send messages to the websocket server and doesn't need to receive any. php后端仅需要将消息发送到websocket服务器,而无需接收任何消息。

You could make your php and your node communicate over HTTP. 您可以使您的php和您的节点通过HTTP进行通信。

You already have express installed in your node application so let's define a little API 您已经在节点应用程序中安装了express,因此让我们定义一些API

Define a middleware to ensure that is your php calling the node API 定义一个middleware以确保您的php调用了节点API

/** 
 *  Secure the HTTP calls from PHP
 *  Return a 403 (forbidden) if no token given
 * */
app.use(function (req, res, next) {
    // Do your logic to secure your API if your node application is visible from the internet
    // You don't want malicious people to send event as your php ;)
    if(false) {
        res.sendStatus(403);
        return;
    }

    next(); // it's ok let the process continue
});

Define a simple route that answer on GET http://localhost:3000/your/endpoint 定义在GET http:// localhost:3000 / your / endpoint上回答的简单路由

app.get('/your/endpoint', function(req, res) {
    io.sockets.emit('update');

    res.sendStatus(200);
});

If you want to use the body of the HTTP request, you could use library like body-parser that allow you to do stuff like below. 如果要使用HTTP请求的主体,则可以使用诸如body-parser类的库,该库允许您执行以下操作。 This route answer at POST http://localhost:3000/post/example POST此路线答案http:// localhost:3000 / post / example

/** Enable the parsing of request body */
app.use(bodyParser.json());

app.post('/post/example', function(req, res) {
    let body  = req.body,
        event = body.event,
        data  = body.data || {};

    if(undefined === event) {
        res.sendStatus(400);
        return;
    }
   ...
}

WebSocket is a complex protocol that you will not be able to use with raw PHP. WebSocket是一个复杂的协议,您将无法与原始PHP一起使用。 Here are some links, just for information: 以下是一些链接,仅供参考:


If you want a communication between your PHP and WebSocket server, then you can use a PHP library that helps you in that way. 如果要在PHP和WebSocket服务器之间进行通信,则可以使用以这种方式帮助您的PHP库。 Here is a little list of known PHP library that do the job: 这是完成此工作的已知PHP库的一些清单:

For more information, please checkout their documentation. 有关更多信息,请查阅其文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM