简体   繁体   中英

How Node.js + Socket.io receive data from PHP

I have a small project that lets the user upload realtime data. Since I am a PHP dev, I find it very hard to work with Node.js and Socket.io. What I did is, I use PHP as the main backend of my application. It is the one who will receive data from the users and save it to the database. After the user submitted data, PHP will then send the data to node.js application which will be the one who will emit to all connected users through socket.io. But how can I do this? I mean how will node.js no that there is a new data? I want PHP to send data (via POST) to Nodejs, then socket.io will broadcast it.

I cannot find any working example. BTW, the data that PHP will send to Node.js will be in JSON form. Someone ask it here: NodeJS receiving data from PHP server but I cannot understand how it works.

Here's a simple Node.js application that creates a REST api that you can post JSON to:

app.js:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.use(bodyParser.json({type: 'application/vnd.api+json'}));

var router = express.Router();

function dataHandler(req, res) {
    // the 'body' variable will contain the json you've POSTed:
    var body = req.body;
    // your socket.io logic would go around here.
    console.log(body.message);
    res.send("ok");
}

router.route('/receive')
    .post(dataHandler);
app.use('/api', router);

app.listen(3000, function() {
    console.log('Express started at port 3000');
});

package.json:

{
  "name": "node-test",
  "descirption": "Node test",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "body-parser": "^1.10.0",
    "express": "^4.4.3"
  }
}

To get it working, follow these steps (assuming here that you have Node installed):

  1. Create a new directory, and create the two above files in it
  2. run npm install . this will read package.json and install the required dependencies
  3. run node app.js
  4. Send to URL http://localhost:3000/api/receive the following JSON message with POST:

    { "message": "Hello world" }

Check the console output where you ran the node app.js . it should have logged the "Hello world" message.

What you're creating is a simple REST api. To learn more about how to do REST apis with Node.js and gain understanding of what's going on in the example app I posted, you can Google 'Node.js rest api tutorial'. You'll typically have to cherry-pick what you read as some of the tutorials will explain how to set up database, etc. Here's one that goes through most of what is done in the example above.

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