Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebSocket on node js server (ReferenceError)

According to the npm docs :

ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and server implementation.

So I have installed it

npm install ws

and tried a little test on Node js file :

const Websocket = require('ws');

const ws = new WebSocket('ws://www.host.com/path');

but I receive an error :

ReferenceError : WebSocket is not defined

What am i doing wrong please ?

EDIT :

It was just a typing error.

I used

const Websocket = require('ws');

const ws = new WebSocket('ws://www.host.com/path');

But I have to use :

const WebSocket = require('ws');  // WebSocket with camelCase...

const ws = new WebSocket('ws://www.host.com/path');
like image 663
Olivier J. Avatar asked Nov 23 '25 15:11

Olivier J.


1 Answers

Your using the client logic on the server, try

const WebSocket = require('ws').Server;

const ws = new WebSocket({ port: 8080 });
like image 124
James Avatar answered Nov 25 '25 11:11

James