使用socket.io和node.js建立websocket连接时遇到错误。这是我的环境:
尝试连接websocket时会引发以下错误:
TypeError: Cannot read property 'on' of undefined
at PerMessageDeflate.decompress (C:\ng-project\node_modules\ws\lib\PerMessageDeflate.js:242:37)
at Receiver.applyExtensions (C:\ng-project\node_modules\ws\lib\Receiver.js:362:54)
at C:\ng-project\node_modules\ws\lib\Receiver.js:508:14
at Receiver.flush (C:\ng-project\node_modules\ws\lib\Receiver.js:347:3)
at Receiver.opcodes.1.finish (C:\ng-project\node_modules\ws\lib\Receiver.js:541:12)
at Receiver.expectHandler (C:\ng-project\node_modules\ws\lib\Receiver.js:493:33)
at Receiver.add (C:\ng-project\node_modules\ws\lib\Receiver.js:103:24)
at Socket.realHandler (C:\ng-project\node_modules\ws\lib\WebSocket.js:825:20)
at ZoneDelegate.invokeTask (C:\ng-project\node_modules\zone.js\dist\zone-node.js:265:35)
at Zone.runTask (C:\ng-project\node_modules\zone.js\dist\zone-node.js:154:47)
at Socket.ZoneTask.invoke (C:\ng-project\node_modules\zone.js\dist\zone-node.js:335:33)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:177:18)
at Socket.Readable.push (_stream_readable.js:135:10)
at TCP.onread (net.js:542:20)
查看ws
模块,我可以看到抛出错误的代码行:
this._inflate.on('error', onError).on('data', onData);
_inflate
是由前面几行InflateRaw
创建的zlib zlib.createInflateRaw({...})
实例。问题是InflateRaw#on
函数在我的环境中返回undefined
。
我已经尝试安装其他版本的Node来解决这个问题而没有任何运气...改变ws
包对我来说不是一个可接受的解决方法。
编辑1: 添加引发错误的源代码。
io.on('connection', (socket) => {
// Listen for verification subscription requests
log.debug("Established socket connection " + socket.id);
socket.on('verify subscribe', (msg) => {
log.debug("Recieved 'verify subscribe' message: " + JSON.stringify(msg));
// Do stuff....
});
});
此代码在错误之前输出以下日志消息:
[2016-12-30T19:08:09.219Z] DEBUG: Established socket connection -g9oZM6pEqpFyU_BAAAA
[2016-12-30T19:08:09.275Z] DEBUG: Recieved 'verify subscribe' message: {"token":"short-ish.token","authorization":"long.auth-token"}
答案 0 :(得分:0)
发现此问题是zone.js的错误,并已在更高版本(> 0.7.0)中修复。这个问题在GitHub上跟踪:angular/zone.js#508。
答案 1 :(得分:-1)
您尚未设置io
。确保你已经完成了
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
来自文档聊天示例 - http://socket.io/get-started/chat/
如果您未设置io
,则会undefined
。
var app = require('http').createServer(handler)
var io = require('socket.io')(app);