后端代码

const http = require('http');
const WebSocket = require('ws');
const url = require('url');
var fs = require("fs");

const server = http.createServer(function(request, response) {
    var file = fs.createReadStream(__dirname + '/index.html');
    response.writeHead(200, {'Content-Type' : 'text/html;charset=utf8'});
    file.pipe(response);
});

const wss = new WebSocket.Server({ noServer: true });
wss.on('connection', function connection(ws, req) {
  wss.on('message', function incoming(data) {
    sendAll(data)
  });
  
  function sendAll(mes) {
    wss.clients.forEach(function each(client) {
      if (client.readyState === WebSocket.OPEN) {
        client.send(mes);
      }
    });
  }
});

server.on('upgrade', function upgrade(request, socket, head) {
  const pathname = url.parse(request.url).pathname;
  if (pathname === '/ws') {
    wss.handleUpgrade(request, socket, head, function done(ws) {
        wss.emit('connection', ws, request);
    });
  } else {
    socket.destroy();
  }
});

server.listen(80);

前端代码调用如下

new WebSocket('ws://localhost/ws')

完整代码查看github

https://github.com/ColdDay/websocket-chat


--------------

原创文章出自 木法传,如转载请注明本文链接:https://www.mofazhuan.com/466.html

--------------