创建 Socket 连接很简单,一行代码即可。
let ws = new WebSocket('wss://example.com/');
如果服务器采用 SSL,只需要将 ws:// 替换成 wss://
let ws = new WebSocket('wss://echo.websocket.org/');
然后是通过回调函数获取服务器消息以及对连接状态进行捕捉。
// 成功连接时触发
ws.onopen = function() {
console.log('连接成功.');
this.send('{"event":"subscribe", "channel":"guest"}');
};
// 有新消息时触发
ws.onmessage = function(e) {
console.log('服务器发来消息: ', e.data);
};
// 发生错误触发
ws.onerror = function(e) {
console.log('连接错误: ', e);
};
// 连接关闭触发
ws.onclose = function(e) {
console.log('连接中断: ', e);
};
心跳检测
防止长时间不通讯导致连接被关闭,所以每隔一段时间就给服务器发送消息进行检验。一般用定时器既可以实现。
// 这里封装了一个实现心跳的构造函数
// 同时传入一个回调函数给定时器执行
function Heartbeat(func) {
// 保存定时器
this.timer = null;
// 定时器间隔
this.interval = 30*1000;
// 心跳启动
this.start = function() {
clearInterval(this.timer);
this.timer = setInterval(func, this.interval);
};
// 停止
this.stop = function() {
clearInterval(this.timer);
};
}
然后是启动心跳,在客户端与服务器连接成功后就应该设置心跳,所以在 onopen 回调中实现。
还有一个问题就是建立连接就应该立即发送一条消息,毕竟启动定时器后发送心跳也是有时间间隔的。
// 在 WebSocket对象实例上追加方法
ws.sendHeartbeat = function() {
this.send('{"event":"heartbeat", "channel":"guest", "user": "user03"}');
};
ws.onopen = function() {
// 连接后立即发一条消息刷存在感【必要】
this.send('{"event":"subscribe", "channel":"guest"}');
// sendHeartbeat 绑定到 ws 对象上可以直接调用this.send发送消息
this.heartbeat = new Heartbeat(this.sendHeartbeat.bind(this));
this.heartbeat.start();
};
另外连接断开的时候别忘记关闭定时器。
ws.onclose= function() {
this.heartbeat.stop();
};
到此结束。websocket 爽归爽,但一定别忘了处理断连,因为网络一波动特容易掉线,所以代码中必须做好重连的准备。