Skip to content

Instantly share code, notes, and snippets.

@dirkk0
Last active November 29, 2023 08:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dirkk0/c03a800c400259045aad4442f5b0648a to your computer and use it in GitHub Desktop.
Save dirkk0/c03a800c400259045aad4442f5b0648a to your computer and use it in GitHub Desktop.
nodejs websocket with ws and http - full minimal example
// starter was this very helpful post from @lpinca
// https://github.com/websockets/ws/issues/2052#issuecomment-1142529734
// installation: npm install ws
const WebSocketServer = require("ws");
const http = require('http');
const PORT = process.env.PORT || 8084;
const data = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
(function () {
var ws = new WebSocket('ws://localhost:8084');
ws.onopen = function () {
console.log('open');
setInterval(() => {
ws.send('message from client');
}, 2000)
};
ws.onmessage = function (msg) {
console.log('client received', msg.data);
};
})();
</script>
</body>
</html>`;
const server = http.createServer((req, res) => {
if (req.method === 'GET') {
res.setHeader('Content-Type', 'text/html');
res.end(data);
}
})
const wss = new WebSocketServer.Server({ server });
wss.on('connection', function (ws) {
console.log('connected');
ws.on('error', console.error);
ws.on('message', function message(data) {
console.log('server received: %s', data);
});
setInterval(() => {
ws.send('message from server');
}, 1000);
});
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment