websocket 连不上
发布于 8 年前 作者 wangjinnana 5294 次浏览 来自 问答

刚安装了ws,试着库中的例子发现连接不了,也不报错,有没有人遇到过这个问题,怎么解决的 浏览器为chrome var WebSocketServer = require(’…/node_modules/ws’).Server , http = require(‘http’) , express = require(‘express’) , //app = express.createServer(); app = express();

app.use(express.static(__dirname + ‘/public’)); app.listen(8080);

var wss = new WebSocketServer({server: app}); wss.on(‘connection’, function(ws) { var id = setInterval(function() { ws.send(JSON.stringify(process.memoryUsage()), function() { /* ignore errors */ }); }, 100); console.log(‘started client interval’); ws.on(‘close’, function() { console.log(‘stopping client interval’); clearInterval(id); }); });

index.html <!DOCTYPE html> <html> <head> <style> body { font-family: Tahoma, Geneva, sans-serif; }

  div {
    display: inline;
  }
</style>

</head> <body> <strong>Server Stats</strong><br> RSS: <div id=‘rss’></div><br> Heap total: <div id=‘heapTotal’></div><br> Heap used: <div id=‘heapUsed’></div><br> <script> if (‘WebSocket’ in window) { alert(“in window”); } function updateStats(memuse) { document.getElementById(‘rss’).innerHTML = memuse.rss; document.getElementById(‘heapTotal’).innerHTML = memuse.heapTotal; document.getElementById(‘heapUsed’).innerHTML = memuse.heapUsed; }

  var host = window.document.location.host.replace(/:.*/, '');
  alert(host);
  var ws = new WebSocket('ws://' + host + ':8080');
  ws.onopen=function() {
  alert("open");
  };
  ws.onmessage = function (event) {
  alert("hello");
    updateStats(JSON.parse(event.data));
  };
</script>

</body> </html>

2 回复

ws#expressjs-example

var server = require('http').createServer()
  , url = require('url')
  , WebSocketServer = require('ws').Server
  , wss = new WebSocketServer({ server: server })
  , express = require('express')
  , app = express()
  , port = 4080;

app.use(function (req, res) {
  res.send({ msg: "hello" });
});

wss.on('connection', function connection(ws) {
  var location = url.parse(ws.upgradeReq.url, true);
  // you might use location.query.access_token to authenticate or share sessions
  // or ws.upgradeReq.headers.cookie (see http://stackoverflow.com/a/16395220/151312)

  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.send('something');
});

server.on('request', app);
server.listen(port, function () { console.log('Listening on ' + server.address().port) });

今天在公司成功了,怀疑是ws的版本问题,晚上回去看一下

回到顶部