Created
May 31, 2020 20:25
-
-
Save ridomin/9fd56e71715c392cc83ef9d15e344d75 to your computer and use it in GitHub Desktop.
WebSocketsDemo
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
var wsUri = "ws://127.0.0.1:8999"; | |
ws = new WebSocket(wsUri); | |
ws.onopen = (e) => console.log(e) | |
ws.onmessage = (e) => console.log(e) |
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
import express from 'express'; | |
import http from 'http'; | |
import WebSocket from 'ws'; | |
const app = express(); | |
app.use(express.static('ui')); | |
const server = http.createServer(app); | |
const wss = new WebSocket.Server({ server }); | |
app.get('/', function (req, res) { | |
res.sendFile( __dirname + "/" + "index.html" ); | |
}) | |
wss.on('connection', (ws) => { | |
ws.on('message', (message) => { | |
console.log('received: %s', message); | |
ws.send(`Hello, you sent -> ${message}`); | |
}); | |
ws.send('Hi there, I am a WebSocket server'); | |
}); | |
server.listen(process.env.PORT || 8999, () => { | |
console.log(`Server started on port ${server.address().port} :)`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment