关于WebSocket
最近在学习WebSocket!但是总是遇到握手连接失败的问题!火狐浏览器给出的错误提示是 Firefox 无法建立到 ws://localhost:3000/ 服务器的连接。 并且错误直接定位到前端代码的这句:var ws = new WebSocket(‘ws://localhost:3000’); 自己反复调试还是不清楚哪里出了问题!希望得到帮助! 下面贴出服务器端代码和客户端代码: app.js /**
- @todo require dependencies
- @author yiwei */ var express = require(‘express’), http = require(‘http’), wsio = require(‘websocket.io’);
/**
- @todo create app */ var app = express(http.createServer());
/**
- @todo 将websocket.io绑定到express上,这样它就能处理WebSocket请求了 */ var ws = wsio.attach(app);
app.use(express.static(‘public’));
/**
- @todo listening on connections */ ws.on(‘connection’, function (socket) { socket.on(‘message’, function (msg) { consoel.log('mogt: ’ + msg); socket.send(‘pong’); }); });
/**
- @todo listen port */ app.listen(3000, function () { console.log(‘success listen port: 3000’); });
client.js var lastMessage;
window.onload = function () { /* create socket / var ws = new WebSocket(‘ws://localhost:3000’); ws.onopen = function () { alert(‘open’); / send first ping */ ping(); };
ws.onmessage = function (ev) {
console.log('got: ' + ev.data);
document.querySelector('#latency').innerHTML = new Date - lastMessage;
//ping again
ping();
};
function ping() {
lastMessage += new Date;
ws.send('ping');
};
};
1 回复
自己搞定了,构建服务器端出错了。以前总是往客户端找错!!结果南辕北辙!!