我是 javascript 新手,正在尝试开发一个 react.js 应用程序,包括通过 socketcluster 框架进行通信。客户端不应在浏览器中运行,而应在后台单独的 javascript 文件中运行。
为了实现这一点,我为服务器(https://github.com/SocketCluster/socketcluster)和客户端(https://github.com/SocketCluster/socketcluster-client)安装了必要的模块。
我按照说明操作,服务器和客户端之间的通信(嵌入在 html 中的 javascript 代码,在浏览器中运行)正常工作。但是,当我尝试使用“node gbam-client.js”在单独的 javascript (gbab-client.js) 文件中运行客户端时,它没有。我将非常感谢您的帮助!
gbab-client.js 的内容:
const socketClusterClient = require('socketcluster-client/socketcluster');
const options = {
port: 2222
};
// Initiate the connection to the server
const socket = socketClusterClient.connect(options);
console.log('Connecting...');
socket.on('connect', function () {
console.log('CONNECTED');
});
// Listen to an event called 'rand' from the server
socket.on('rand', function (num) {
console.log('RANDOM: ' + num);
});
错误信息:
$ node gbam-client.js
C:\...\node_modules\socketcluster-client\socketcluster.js:1306
return new WebSocket(uri, null, options);
^
TypeError: WebSocket is not a constructor
at createWebSocket (C:\...\node_modules\socketcluster-client\socketcluster.js:1306:12)
at new SCTransport (C:\...\node_modules\socketcluster-client\socketcluster.js:1337:18)
at SCClientSocket.connect.SCClientSocket.open (C:\...\node_modules\socketcluster-client\socketcluster.js:558:22)
at new SCClientSocket (C:\...\node_modules\socketcluster-client\socketcluster.js:433:10)
at Object.create (C:\...\node_modules\socketcluster-client\socketcluster.js:198:31)
at Object.module.exports.create (C:\...\node_modules\socketcluster-client\socketcluster.js: 14:18)
at Object.<anonymous> (C:\...\gbam-client.js:12:36)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
更新:
我找到了解决方案。require 的目的地不对。
这是更正后的代码(gbam-client.js):
const socketClusterClient = require('socketcluster-client');
const options = {
hostname:'localhost',
port: 2222
};
...