【发布时间】:2019-01-24 13:59:13
【问题描述】:
我开始使用节点 js。到目前为止一切都很好。直到今天。 我在玩 websockets,我能够在服务器和浏览器之间建立连接。但是,我无法使用 ws.send('something'); 从服务器向客户端发送消息。 在几乎每个示例中,我都发现使用了该方法,而在我的情况下,它似乎不起作用。 有人可以解释一下为什么吗?
const express = require('express');
const path = require('path');
const WebSocket = require('ws').Server;
const router = express.Router();
const SerialPort = require('serialport');
const barCode = new SerialPort('COM50', {
baudRate: 57600
});
// --------- SETUP WS ---------
var wsport = 8085;
var ws = new WebSocket({port: wsport});
ws.on('connection', function open() {
console.log('ws connection has been established.');
// ws.send('something'); this line is not working!
});
// !!-- BarCode:: Log errors to console when they occur.
barCode.on('error', function(err) {
console.log('Error: ', err.message);
});
barCode.on('data', function (data) {
console.log('Barcode received:', data);
ws.send('received barcode');
});
// --------- SETUP EXPRESS ---------
var app = express(); // Define the application object
var port = 4000; // Specify the port to listen to
router.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/public/index.html'));
//__dirname : It will resolve to your project folder.
});
router.get('/offline',function(req,res){
res.sendFile(path.join(__dirname+'/public/offline.html'));
//__dirname : It will resolve to your project folder.
});
app.use(express.static('public'));
app.use('/', router);
app.listen(process.env.port || port);
console.log('Webserver running at port ' + port);
module.exports = app;
【问题讨论】:
-
In almost every example I can find the methode is used,不是来自文档,它不是。 npmjs.com/package/ws#sending-and-receiving-text-data IOW:尝试 ->ws.on('connection', function open(ws) {在您的情况下,将名为 ws 的 var 更改为 wss 以匹配文档并避免混淆也可能值得。
标签: javascript node.js websocket serial-port