index.html:
<html> <head></head> <body> <div id="message"></div> <script> let ws = new WebSocket("ws://localhost:5000/"); ws.onopen = () => ws.send("hello server!"); ws.onmessage = ev => { const $message = document.getElementById("message"); $message.textContent = `ws://localhost:5000/ response: ${ev.data}`; }; </script> </body> </html>
const express = require("express"); const http = require("http"); const WebSocket = require("ws"); const app = express(); const server = http.createServer(app); const wss = new WebSocket.Server({ server }); wss.on("connection", ws => { ws.on("message", message => { console.log(`received: ${message}`); ws.send("hello client"); }); }); server.listen(5000, () => console.log("ws server listening on localhost:5000"));