Last active
November 29, 2023 08:12
-
-
Save dirkk0/c03a800c400259045aad4442f5b0648a to your computer and use it in GitHub Desktop.
nodejs websocket with ws and http - full minimal example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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