I am new to javascript and am trying to develop a react.js application including communication over socketcluster framework. The client should not run in the browser but in a separate javascript file in the background.
To realize this, I have installed the necessary modules for server (https://github.com/SocketCluster/socketcluster) and client (https://github.com/SocketCluster/socketcluster-client).
I followed the instructions and the communication between server and client (javascript code embedded in html, run in browser) worked. But when I try to run the client in a seperate javascript (gbab-client.js) file with "node gbam-client.js", it doesn't. I would be very grateful for your help!
Content of 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);
});
Error Message:
$ 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)
UPDATE:
I found the solution. The destination of require wasn't right.
This is the corrected code (gbam-client.js):
const socketClusterClient = require('socketcluster-client');
const options = {
hostname:'localhost',
port: 2222
};
...
Maybe your ws (WebSocket library) version is not compatible with socketcluster, try to update it WS