刚安装了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
div {
display: inline;
}
</style>
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>
回复 (2)
S
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) });
W
今天在公司成功了,怀疑是ws的版本问题,晚上回去看一下
参与回复
登录后即可参与回复。登录