How to use the Server function from ws

Find comprehensive JavaScript ws.Server code examples handpicked from public code repositorys.

ws.Server is a class in the WebSocket library ws that can be used to create a WebSocket server.

272
273
274
275
276
277
278
279
280
281
3. Когда сообщение получено: перебрать клиентов `clients` и отправить его всем.
4. Когда подключение закрыто: `clients.delete(socket)`.

```js
const ws = new require('ws');
const wss = new ws.Server({noServer: true});

const clients = new Set();

http.createServer((req, res) => {
fork icon878
star icon0
watch icon47

+ 3 other calls in file

28
29
30
31
32
33
34
35
36
37
  return options.onListening({ address: getServerAddress(wsServer) });
}

getAvailablePort(3030, 4000).then(
  port => {
    wsServer = new WebSocket.Server({ port });
    webSockets = [];

    wsServer.on('connection', function connection(newWebSocket) {
      const id = webSockets.length;
fork icon628
star icon0
watch icon161

How does ws.Server work?

ws.Server is a class in the ws library that allows creating a WebSocket server, which listens to incoming WebSocket connections, accepts them, and allows sending/receiving messages between the server and clients in real-time using the WebSocket protocol. When creating an instance of ws.Server, it takes an object with configuration options such as port number, server host, path, etc., and once created, it can listen to incoming connections and respond to WebSocket events such as connection, message, and close.

41
42
43
44
45
46
47
48
49
50
var ShareDB = require('sharedb')
var WebSocketJSONStream = require('@teamwork/websocket-json-stream')

var app = express()
var server = http.createServer(app)
var webSocketServer = WebSocket.Server({server: server})

var backend = new ShareDB()
webSocketServer.on('connection', (webSocket) => {
  var stream = new WebSocketJSONStream(webSocket)
fork icon447
star icon0
watch icon110

+ 9 other calls in file

112
113
114
115
116
117
118
119
120
121
const { createServer } = require('http');

const app = require('express')();

const server = createServer(app);
const ws = new Server({ server });

server.listen(4200);

ws.on('connection', socket => {
fork icon391
star icon0
watch icon92

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const WebSocket = require("ws");

const server = new WebSocket.Server({ port: 8080 });

server.on("connection", (socket) => {
  console.log("Client connected");

  socket.on("message", (message) => {
    console.log(`Received message: ${message}`);
  });

  socket.on("close", () => {
    console.log("Client disconnected");
  });
});

This code creates a WebSocket server that listens on port 8080. Whenever a client connects to the server, it logs a message to the console. When a message is received from the client, it logs the message to the console as well. When the client disconnects, it logs a message to the console.

7
8
9
10
11
12
13
14
15
app.use(function (req, res) {
    res.send({ msg: "hello" });
});

const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

wss.on('connection', function connection(ws) {
    console.log("ws connected");
fork icon132
star icon227
watch icon29

101
102
103
104
105
106
107
108
109
110
    }
    console.log('Swarm server started port', argv.port);
});

// start WebSocket server
var wsServer = new ws_lib.Server({
    server: httpServer
});

// accept pipes on connection
fork icon79
star icon288
watch icon0

+ 3 other calls in file

17
18
19
20
21
22
23
24
25
26
  key: fs.readFileSync('/home/node/app/bulletjournal.us.key'),
  cert: fs.readFileSync('/home/node/app/bulletjournal.us.cert')
};

// @ts-ignore
const wss = new ws.Server({ noServer: true })

const server = https.createServer(options,(request, response) => {
  response.writeHead(200, { 'Content-Type': 'text/plain' })
  response.end('okay')
fork icon43
star icon138
watch icon22

0
1
2
3
4
5
6
7
8
9
const net = require('net');
const fs = require('fs');
const path = require('path');
const http = require('http');
const WebSocket = require('ws');
const WebSocketServer = WebSocket.Server;
const parseArgs = require('minimist');
const { Encryptor } = require('./encrypt');

const options = {
fork icon0
star icon560
watch icon39

+ 7 other calls in file

130
131
132
133
134
135
136
137
138
        })
    }
}

function startServer() {
    const wss = new WebSocket.Server({ port })
    console.log('franchise-client listening on port:', port)
    wss.on('connection', (ws) => {
        console.log('opened connection')
fork icon279
star icon0
watch icon104

+ 9 other calls in file

316
317
318
319
320
321
322
323
324
325
```ts
// minimal version of `import { useServer } from 'graphql-ws/lib/use/ws';`

import { WebSocketServer } from 'ws'; // yarn add ws
// import ws from 'ws'; yarn add ws@7
// const WebSocketServer = ws.Server;
import { makeServer, CloseCode } from 'graphql-ws';
import { schema } from './my-graphql-schema';

// make
fork icon129
star icon0
watch icon19

+ 3 other calls in file

4
5
6
7
8
9
10
11
12
const serialize = x => util.inspect(x, { depth: null });
const log = (message) => {
  console.log(`${new Date().toISOString()}: ${message}`);
};

const lambdaServer = new WebSocket.Server({ port: 8080 });
const userServer = new WebSocket.Server({ port: 9229 });

let socketCache = [];
fork icon14
star icon290
watch icon15

+ 11 other calls in file

19
20
21
22
23
24
25
26
27
28
var app = express();
var httpServer = require('http').createServer(app);
httpServer.listen(8000);

const WebSocket = require('ws');
const wss = new WebSocket.Server({
  server: httpServer
});

wss.on('connection', function(socket){
fork icon20
star icon82
watch icon4

+ 3 other calls in file

17
18
19
20
21
22
23
24
25
26
    current = 0,
    start = 0,
    end = 0,
    wss;

wss = new WebSocket.Server({ port: PORT });
console.log('Server ready on port '+ PORT);
wss.on('connection', function connection(ws) {
    console.log('Socket connected. sending data...');
    const wsstream = WebSocket.createWebSocketStream(ws);
fork icon99
star icon434
watch icon15

214
215
216
217
218
219
220
}

// ws server, handles upgrade requests for http server

function addWebsocket(server) {
  const wss = new WebSocket.Server({noServer: true});
  wss.on('connection', handleConnection);
fork icon85
star icon0
watch icon30

+ 11 other calls in file

147
148
149
150
151
152
153
154
155
156



module.exports = (httpServer) => {

        const wss = new WebSocket.Server({server : httpServer});

        wss.on('connection',(ws, req) => {
                        let sessionId = queryString.parse(URL.parse(req.url).query).sessionId;
                        ws.id = sessionId;
fork icon79
star icon173
watch icon10

+ 3 other calls in file

15
16
17
18
19
20
21
22
23
class RpcWsServer extends EventEmitter {

    constructor(http_server) {
        super();

        const ws_server = new WS.Server({
            server: http_server,
            perMessageDeflate: false,
        });
fork icon70
star icon229
watch icon17

1
2
3
4
5
6
7
8
9
10
const WebSocket = require('ws');
const events = require('../modules/events');
const Diagram = require('../models/diagram');

function start(config) {
        let     wss = new WebSocket.Server({ 
                port: parseInt(config.port || 5000) + 1,
                clientTracking: true
        });
        
fork icon8
star icon23
watch icon4

+ 8 other calls in file

113
114
115
116
117
118
119
120
121
122
}

class PairDropServer {

    constructor() {
        this._wss = new WebSocket.Server({ server });
        this._wss.on('connection', (socket, request) => this._onConnection(new Peer(socket, request)));

        this._rooms = {};
        this._roomSecrets = {};
fork icon39
star icon727
watch icon6

12
13
14
15
16
17
18
19
20
21
    output: process.stdout,
    terminal: false
});

// Create a WebSocket server
const wsServer = new ws.Server({ noServer: true });
wsServer.on('connection', socket => {
    function sender(line) {
        socket.send(line);
    }
fork icon0
star icon4
watch icon2

+ 9 other calls in file