简体   繁体   中英

How would I use Socket.io on a dedicated node.js server on a php site?

For a web application coded in PHP, I am powering a lot of the functionality that would traditionally utilize AJAX, like real-time chat, with Socket.io. In order to use Websockets without straining Apache servers, I have servers running node.js specifically for the Websocket connections. I intend to use DNode to allow the php scripts to call the node.js Websocket functions. How would I do this? Please provide a simple example if possible.

I realize that this may not be the most efficient structure, but because of the large number of connections utilizing real-time functionality at the same time, running Websockets from PHP would be very server-intensive. I also know that there are other ways of achieving real-time communication between server and client, like long polling and forever iframes, but there are specific reasons behind the choice of Websockets.

This is an alternative to send data from PHP to Node.js:

<?php

$ch = curl_init();

$data = array('name' => 'Foo', 'file' => '@/home/user/img.png');

curl_setopt($ch, CURLOPT_URL, 'http://localhost:8082/test'); /* Nodejs */
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
?>

More info here .

In app.js

app.post('/test', function(req, res){
    console.log("name: " + req.body.name);
...

I hope that is helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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