Created
November 24, 2024 05:23
-
-
Save iKunalChhabra/04d5717363ee316348bb2cfd4ab65cf2 to your computer and use it in GitHub Desktop.
WebSocket in Express Node JS
This file contains hidden or 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
| 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 }); | |
| const PORT = process.env.PORT || 3000; | |
| app.get('/', (req, res) => { | |
| res.sendFile(__dirname + '/index.html'); | |
| }); | |
| wss.on('connection', (ws) => { | |
| console.log('A user connected'); | |
| ws.on('message', (msg) => { | |
| const message = msg.toString(); | |
| console.log('Message received:', message); | |
| ws.send('Server received: ' + message); | |
| }); | |
| ws.on('close', () => { | |
| console.log('User disconnected'); | |
| }); | |
| }); | |
| server.listen(PORT, () => { | |
| console.log(`Server running on port ${PORT}`); | |
| console.log(`WebSocket connection address: ws://localhost:${PORT}`); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment