1

Господа, как можно заставить вебсокет-сервер для открывших сайт обычным образом в браузере (не по 9030 порту) показывать обычную простенькую html-страницу? Пытался по примерам с express app.use(express.static("/public")), но что-то я делаю глобально не так. Результат нулевой. Мб может кто поделиться готовым рабочим примером?

const http = require('http');
const server = http.createServer();
const WebSocket = require('ws');
var port = process.env.PORT || 9030;
const wss = new WebSocket.Server({ port: port, verifyClient: function(info, done) {
    //проверка клиента
    }, server: server
});

server.on('upgrade', function upgrade(request, socket, head) {
    wss.handleUpgrade(request, socket, head, function done(ws) {
        wss.emit('connection', ws, request);
    });
});

wss.on('connection', function(ws, req) {
        ws.on('close', function() {

        });
});

Сейчас выводится Upgrade Required.

Скриншот

2
  • вам нужно сделать это под нативным http или под express? 13 мая 2021 в 16:36
  • @nörbörnën, разницы нет, чем проще и чем меньше зависимостей — тем лучше. Примеры в основном находил на express.
    – Turambar
    13 мая 2021 в 16:42

1 ответ 1

2

Вы просили "проще и без зависимостей".

Сервер, index.js

const path = require('path');
const fs = require('fs');
const http = require('http');
const WebSocket = require('ws');

const port = +(process.env.PORT || 9030);

const server = http.createServer((req, res) => {
  //
  // Вот тут происходит отдача index.html
  //
  res.writeHead(200, { 'Content-Type': 'text/html' });
  const stream = fs.createReadStream(path.join(__dirname, '/index.html'));
  stream.pipe(res);

});

// Запуск сервера
server.listen(port, () => 'Server up');


// Работы с ws-соединениями
const wss = new WebSocket.Server({
  noServer: true,
  verifyClient(info, done) {
    console.log('verifyClient', info);
    done(true);
  },
});

server.on('upgrade', (request, socket, head) => {
  wss.handleUpgrade(request, socket, head, (ws) => {
    wss.emit('connection', ws, request);
  });
});

wss.on('connection', (ws, req) => {
  setInterval(() => ws.send(Date.now()), 1000);
});

Клиентская часть, index.html

Положить рядом с index.js

<!DOCTYPE html>
<html>
  <head>
    <title>Hello</title>
    <script>
      const ws = new WebSocket('ws://localhost:9030');
      ws.onopen = function () { console.log('opened') }
      ws.onclose = function () { console.log('close') }
      ws.onerror = function (err) { console.log(err) }
      ws.onmessage = function (msg) {
        const li = document.createElement('li');
        li.innerHTML += msg.data
        document.getElementById('ol').prepend(li);
      }
    </script>
  </head>
  <body><h1>ru.SO</h1><ol id="ol"></ol></body>
</html>

Результат

Результат на html-странице

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.