【问题标题】:Websocket server: TypeError ws.send() not a functionWebsocket 服务器:TypeError ws.send() 不是函数
【发布时间】: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


【解决方案1】:

这是一个很常见的错误 这里的事情是

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!
});

作为新 Websocket 创建的变量在函数内部无效

ws.on()

所以 ws 不是函数内的有效变量

ws.send() 不是函数,因此出现错误

尝试调用 ws.on() 中的另一个函数,该函数可以访问创建套接字对象的变量 ws

【讨论】:

    【解决方案2】:
    var ws_server = new WebSocket({ port: wsport });
    ws_server.on('connection', (ws_socket) => {
        ws_socket.send('something'); 
    });
    

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 2016-05-07
    • 1970-01-01
    • 2017-10-23
    • 2019-07-19
    • 2023-03-12
    • 2017-08-23
    相关资源
    最近更新 更多