server.js
var path = require('path')
var http = require('http')
var express = require('express')
var WebSocket = require('ws')
const app = express()
const httpServer = http.createServer(app)
const wss = new WebSocket.Server({ server: httpServer })
app.use(express.static(path.join(__dirname, 'public')))
app.get('/', function (req, res) {
res.sendfile(path.join(__dirname, 'public', 'index.html'))
})
wss.on('connection', (client) => {
client.on('message', (message) => {
console.log('message: ', message)
client.send('ok')
})
client.send('connected')
})
httpServer.listen(2999, () => {
console.log('started at http://localhost:2999')
})
public/index.html
<html>
<head>
</head>
<body>
<div id="connection">not connected</div>
<button id="button">Send</div>
<script>
var connection = document.getElementById('connection')
document.getElementById('button').addEventListener('click', function () {
ws.send('message')
})
var ws
function connect() {
console.log('connecting')
connection.innerHTML = 'connecting...'
ws = new WebSocket('ws://localhost:2999')
ws.addEventListener('open', wsOpenEvent)
ws.addEventListener('close', wsCloseEvent)
ws.addEventListener('message', wsMessageEvent)
ws.addEventListener('error', wsErrorEvent)
}
function wsOpenEvent(e) {
console.log('connected')
connection.innerHTML = 'connected'
}
function wsCloseEvent(e) {
console.log('close')
connection.innerHTML = 'disconnected'
setTimeout(() => connect(), 5000)
}
function wsMessageEvent(e) {
console.log('message', e)
}
function wsErrorEvent(e) {
console.log('error', e)
}
connect()
</script>
</body>
</html>
package.json
{
"name": "web_socket",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"express": "^4.16.3",
"ws": "^6.0.0"
},
"scripts": {
"start": "node server.js"
}
}
я так сделал reconnect )
и модули бы делал через webpack или parcel )