create a wesocket server in javascript

Here is an example code on how to create a WebSocket server in Javascript using the 'ws' package:

First, install the 'ws' package using the following command:

npm install ws

Then, create a file 'websocket-server.js' and paste the following code:

index.tsx
const WebSocket = require('ws');

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

console.log('WebSocket server started');

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

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

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

  socket.on('close', () => {
    console.log('Client disconnected');
  });
});
462 chars
21 lines

This code sets up a WebSocket server on port 8080 and listens for incoming connections. When a client connects, it logs a message to the console and sets up event listeners for incoming messages and disconnection events. When the client sends a message, the server logs the message and sends it back to the client prepended with "You said:".

Start the server by running node websocket-server.js and you can connect to it using a WebSocket client.

related categories

gistlibby LogSnag