How to use the WebSocketServer function from ws

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

ws.WebSocketServer is a class in the ws library for creating WebSocket server instances that can communicate with WebSocket clients over the web.

29
30
31
32
33
34
35
36
37
38
  setSettings
} = require('./wsEvents/index.js');

const app = Express();
const server = createServer(app);
const wsServer = new WebSocketServer({ server });
const wsClients = [];

app.use(fileUpload());
app.use(Express.static(join(__dirname, 'public')));
fork icon148
star icon0
watch icon26

How does ws.WebSocketServer work?

ws.WebSocketServer is a class in the ws library for creating WebSocket server instances that can communicate with WebSocket clients over the web.

When you create a ws.WebSocketServer instance, you can specify options for the server such as the server port and whether to use WebSocket extensions or sub-protocols.

Once the ws.WebSocketServer instance is created, you can attach it to a HTTP server using the ws.WebSocketServer instance's server property. You can also listen for WebSocket connection events using the ws.WebSocketServer instance's on() method and send messages to connected clients using the send() method on the individual WebSocket instances returned by each connection event.

When a client makes a WebSocket connection request to the server, the ws.WebSocketServer instance emits a connection event. You can use the WebSocket instance returned by this event to send and receive messages between the client and server. The WebSocket connection can also be closed using the close() method on the WebSocket instance.

Overall, ws.WebSocketServer provides a convenient interface for creating and managing WebSocket connections between a server and its clients.

29
30
31
32
33
34
35
36
37
38
39
40
41
app.use(express.static("public"));
app.use(sessionParser);


const server = http.createServer(app);


  const wss = new WebSocketServer({ port: 8081 });


  server.on("upgrade", function (request, socket, head) {
    socket.on("error", onSocketError);
    const {pathname} = parse.parse(request.url);
fork icon1
star icon0
watch icon0

20
21
22
23
24
25
26
27
28

this.clients = new Map()
this.streams = new Map()

this.httpServer = createServer()
this.wsServer = new WebSocketServer({ noServer: true })

this.httpTransport = new HttpTransport(this)
this.wsTransport = new WsTransport(this)
fork icon0
star icon2
watch icon1

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const WebSocket = require("ws");

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

// Listen for WebSocket connection events
server.on("connection", (socket) => {
  console.log("New WebSocket connection");

  // Send a welcome message to the client
  socket.send("Hello from WebSocket server!");

  // Listen for messages from the client
  socket.on("message", (message) => {
    console.log(`Received message: ${message}`);

    // Echo the message back to the client
    socket.send(`You said: ${message}`);
  });

  // Listen for WebSocket close events
  socket.on("close", () => {
    console.log("WebSocket connection closed");
  });
});

In this example, we first import the ws library, which contains the ws.WebSocketServer class. We then create a new WebSocket server instance on port 8080. We listen for WebSocket connection events on the server instance, which are emitted whenever a new client connects to the server. We log a message to the console to indicate that a new connection has been established, and then send a welcome message to the client using the send() method on the WebSocket instance returned by the connection event. We also listen for message events on the WebSocket instance, which are emitted whenever the client sends a message to the server. We log the message to the console, and then use the send() method on the WebSocket instance to send an echo of the message back to the client. Finally, we listen for close events on the WebSocket instance, which are emitted whenever the client closes the WebSocket connection. We log a message to the console to indicate that the connection has been closed.

1
2
3
4
5
6
7
8
9
10
11
const http = require('http');
const uuidv4 = require('uuid').v4;


// Spinning the http server and the WebSocket server.
const server = http.createServer();
const wsServer = new WebSocketServer({server});
const port = 8000;
server.listen(port,  () => {
    console.log(`WebSocket server is running on port http://:${port}`);
});
fork icon0
star icon0
watch icon1

+ 2 other calls in file

61
62
63
64
65
66
67
68
69
70
/**
 * 启动 ws 服务
 */
listen() {
  let that = this;
  that.wss = new ws.WebSocketServer({port: that.port, path: that.path});
  that.startCheckTask();

  that.wss.on("connection", function (ws, req) {
    const url = new URL(req.url, exampleBaseUrl);
fork icon0
star icon0
watch icon1

7
8
9
10
11
12
13
14
15
16
17
18
const server = https.createServer({
  cert: fs.readFileSync('/etc/ssl/certs/mobicipfalcon_com.crt'),
  key: fs.readFileSync('/etc/ssl/private/mobicipfalcon_com.key')
});


const wss = new WebSocketServer({ server });


wss.on('connection', function connection(ws) {
  ws.on('error', console.error);
  console.log("Connection Established +++++");
fork icon0
star icon0
watch icon0

+ 3 other calls in file

9
10
11
12
13
14
15
16
17
18
19
20


const { WebSocketServer } = require("ws");
const { constrainedMemory } = require("process");
const app = express();
const server = http.createServer(app);
const wss = new WebSocketServer({ clientTracking: false, noServer: true });
const port = 50020;


app.use(express.json());

fork icon0
star icon0
watch icon0

80
81
82
83
84
85
86
87
88
89
    },
};
const schema = (0, schema_1.makeExecutableSchema)({ typeDefs, resolvers });
const schema2 = graphSchema_js_1.application.createSchemaForApollo();
// ws Server
const wsServer = new ws_1.WebSocketServer({
    server: httpServer,
    path: "/graphql", // localhost:3000/graphql
});
const serverCleanup = (0, ws_2.useServer)({ schema }, wsServer); // dispose
fork icon0
star icon0
watch icon0

90
91
92
93
94
95
96
97
98
99
100
101
102


const server = app.listen(PORT, () =>
  console.log(`server listening on port ${PORT}`)
);


const wss = new ws.WebSocketServer({ server });


wss.on('connection', (connection, req) => {
  const cookies = req.headers.cookie;
  if (cookies) {
fork icon0
star icon0
watch icon0

1
2
3
4
5
6
7
8
9
10
11
12
const uuid = require('uuid');


class PeerProxy {
  constructor(httpServer) {
    // Create a websocket object
    const wss = new WebSocketServer({ noServer: true });


    // Handle the protocol upgrade from HTTP to WebSocket
    httpServer.on('upgrade', (request, socket, head) => {
      wss.handleUpgrade(request, socket, head, function done(ws) {
fork icon0
star icon0
watch icon0

15
16
17
18
19
20
21
22
23
24
});
app.get("/api/v1/auth", (req, res) => { });
const server = app.listen(port, () => {
    console.log(`Socket.IO server running at http://localhost:${port}/`);
});
const wss = new ws_1.WebSocketServer({ server });
wss.on("connection", ws => {
    wss.clients.add(ws);
    ws.on("error", console.error);
    ws.on("message", message => {
fork icon0
star icon0
watch icon0

111
112
113
114
115
116
117
118
119
120
121
122
123
  }
});


const server = app.listen(4040);


const wss = new ws.WebSocketServer({server});
wss.on('connection', (connection, req) => {


  function notifyAboutOnlinePeople() {
    [...wss.clients].forEach(client => {
fork icon0
star icon0
watch icon0

0
1
2
3
4
5
6
7
8
9
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ws_1 = require("ws");
const querystringify_1 = require("querystringify");
const ssh2_1 = require("ssh2");
const wss = new ws_1.WebSocketServer({ port: 80 });
const connections = new Map();
function sendMessage(ws, msg) {
    ws.send('msg|' + msg);
}
fork icon0
star icon0
watch icon0

20
21
22
23
24
25
26
27
28
29
30
  .catch((error) => console.log('error connecting to MongoDB:', error.message))


const start = async () => {
  const app = express()
  const httpServer = createServer(app)
  const wsServer = new WebSocketServer({
    server: httpServer,
    path: '/',
  })
  const serverCleanup = useServer({ schema }, wsServer)
fork icon0
star icon0
watch icon0

160
161
162
163
164
165
166
167
168
169
170
171
  }, 60 * 60 * 1000);
};


/* WebSocket Setup */
const wsConnections = [];
const wss = new WebSocketServer({ server: global.httpServer });


wss.on('connection', (ws) => {
  const id = randomUUID();
  let wsAuthenticated = false;
fork icon0
star icon0
watch icon0

37
38
39
40
41
42
43
44
45
46
47
app.use(bodyParser.json());
app.use(cors(corsOptions));
let httpServer = app.listen(3001, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
const wsServer = new WebSocketServer({ server: httpServer });


wsServer.on('connection', function (connection, req) {
  const userId = parse(req.url, true).query.userId;
  const isAdmin = (parse(req.url, true).query.isAdmin === 'true');
fork icon0
star icon0
watch icon0