express-html-websocket

76 阅读1分钟

page1.html 和 page2.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Paint</title>
  </head>
  <body>
    <h1>Paint</h1>
    <label for="select-app">Select app:</label>
    <select id="select-app">
      <option value="app1">App 1</option>
      <option value="app2">App 2</option>
      <option value="app3">App 3</option>
    </select>
    <script>
      var webSocket = new WebSocket('ws://localhost:3000');
      webSocket.addEventListener('message', function(event) {
        var data = JSON.parse(event.data);
        if (data.event === 'update-select') {
          document.getElementById('select-app').value = data.value;
        }
      });
      document.getElementById('select-app').addEventListener('change', function(event) {
        var value = event.target.value;
        webSocket.send(JSON.stringify({
          event: 'update-select',
          value: value
        }));
      });
    </script>
  </body>
</html>

app.js

const WebSocket = require('ws');
const express = require('express');
const path = require('path');
const app = express();
app.get('/paint1', (req, res) => {
    res.sendFile(path.join(__dirname, 'views', 'paint1.html'));
});
app.get('/paint2', (req, res) => {
    res.sendFile(path.join(__dirname, 'views', 'paint2.html'));
});
app.use(express.static('public')); 
const server = app.listen(3000, () => {
    console.log('Server started on http://localhost:3000');
});
const wss = new WebSocket.Server({ server });
var selectValue = 'app1';
wss.on('connection', function connection(ws) {
  ws.send(JSON.stringify({
    event: 'update-select',
    value: selectValue
  }));
  ws.on('message', function incoming(message) {
    var data = JSON.parse(message);
    if (data.event === 'update-select') {
      selectValue = data.value;
      wss.clients.forEach(function each(client) {
        if (client.readyState === WebSocket.OPEN) {
          client.send(JSON.stringify({
            event: 'update-select',
            value: selectValue
          }));
        }
      });
    }
  });
});