Created
June 18, 2019 13:43
-
-
Save gnosis23/93f690bf0408e31e1883863bcc1a8719 to your computer and use it in GitHub Desktop.
WebSocket demo
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Document</title> | |
</head> | |
<body> | |
<h1>Hello world</h1> | |
<script> | |
// Create WebSocket connection. | |
const socketUrl = new URL('updates', window.location); | |
socketUrl.protocol = 'ws'; | |
const socket = new WebSocket(socketUrl.href); | |
// Connection opened | |
socket.addEventListener('open', function (event) { | |
socket.send('Hello Server!'); | |
}); | |
// Listen for messages | |
socket.addEventListener('message', function (event) { | |
console.log('Message from server ', event.data); | |
}); | |
setTimeout(() => { | |
socket.send("4008123123"); | |
}, 5000); | |
</script> | |
</body> | |
</html> |
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
const WebSocketServer = require('ws').Server; | |
const express = require('express'); | |
const http = require('http'); | |
const path = require('path'); | |
class Server { | |
constructor(port) { | |
this._app = express(); | |
this._port = port; | |
this._appServer = http.createServer(this._app); | |
// external web server | |
this._wss = new WebSocketServer({ | |
server: this._appServer, | |
path: '/updates' | |
}); | |
this._wss.on('connection', (ws) => { | |
ws.on('message', function incoming(message) { | |
console.log('received: %s', message); | |
ws.send(`received: ${message}`); | |
}); | |
ws.send('something'); | |
}); | |
// this._app.use(express.static('../public')); | |
this._app.get('/', (req, res) => { | |
res.sendFile(path.resolve(__dirname, '../public/index.html')); | |
}); | |
} | |
listen() { | |
this._appServer.listen(this._port, () => { | |
console.log('listening on port ' + this._port); | |
}) | |
} | |
} | |
module.exports = Server; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment