上QQ阅读APP看书,第一时间看更新
Running a receiver application on a PC
To run a receiver app on a PC, follow this sequence:
- Create the receiver folder.
- Create the ./receiver/package.json file with the following content:
{
"name": "receiver",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"ws": "^2.3.1"
}
}
- Create the ./receiver/index.js file with the following content:
const WebSocket = require('ws');
const wss = new WebSocket.Server({port: 8080}, function () {
console.log('Websocket server started');
});
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: ', message);
});
// Send message to connected client
ws.send('hello, client');
});
- Create the ./receiver/Dockerfile file with the following content:
FROM node:boron-onbuild
EXPOSE 8080
- Navigate to ./receiver.
- Build an image and run a Docker container:
# Build an image from a Dockerfile
docker build -t websocket-receiver
# Run container in foreground
docker run -p 8080:8080 -it --rm --name websocket-receiver-container websocket-receiver
# Run container in background
# docker run -p 8080:8080 -d --rm --name websocket-receiver-container websocket-receiver
# Fetch the logs of a container
# docker logs -f websocket-sensor-container
# Stop running container
# docker stop websocket-receiver-container
The console output displays that the application is running:
Console output when a receiver app is running
For the source code as shown in this example, go to https://github.com/Altoros/iot-book/.