WebSocket小插件

时间:2023-06-09 09:16:20

一.WebSocket小介绍

随着互联网的发展,传统的HTTP协议已经很难满足Web应用日益复杂的需求了。近年来,随着HTML5的诞生,WebSocket协议被提出,它实现了浏览器与服务器的全双工通信,扩展了浏览器与服务端的通信功能,使服务端也能主动向客户端发送数据。

  我们知道,传统的HTTP协议是无状态的,每次请求(request)都要由客户端(如 浏览器)主动发起,服务端进行处理后返回response结果,而服务端很难主动向客户端发送数据;这种客户端是主动方,服务端是被动方的传统Web模式 对于信息变化不频繁的Web应用来说造成的麻烦较小,而对于涉及实时信息的Web应用却带来了很大的不便,如带有即时通信、实时数据、订阅推送等功能的应 用。在WebSocket规范提出之前,开发人员若要实现这些实时性较强的功能,经常会使用折衷的解决方法:轮询(polling)Comet技术。其实后者本质上也是一种轮询,只不过有所改进。

  轮询是最原始的实现实时Web应用的解决方案。轮询技术要求客户端以设定的时间间隔周期性地向服务端发送请求,频繁地查询是否有新的数据改动。明显地,这种方法会导致过多不必要的请求,浪费流量和服务器资源。

  Comet技术又可以分为长轮询流技术长轮询改进了上述的轮询技术,减小了无用的请求。它会为某些数据设定过期时间,当数据过期后才会向服务端发送请求;这种机制适合数据的改动不是特别频繁的情况。流技术通常是指客户端使用一个隐藏的窗口与服务端建立一个HTTP长连接,服务端会不断更新连接状态以保持HTTP长连接存活;这样的话,服务端就可以通过这条长连接主动将数据发送给客户端;流技术在大并发环境下,可能会考验到服务端的性能。

  这两种技术都是基于请求-应答模式,都不算是真正意义上的实时技术;它们的每一次请求、应答,都浪费了一定流量在相同的头部信息上,并且开发复杂度也较大。

  伴随着HTML5推出的WebSocket,真正实现了Web的实时通信,使B/S模式具备了C/S模式的实时通信能力。WebSocket的工作流程是这 样的:浏览器通过JavaScript向服务端发出建立WebSocket连接的请求,在WebSocket连接建立成功后,客户端和服务端就可以通过 TCP连接传输数据。因为WebSocket连接本质上是TCP连接,不需要每次传输都带上重复的头部数据,所以它的数据传输量比轮询和Comet技术小 了很多。本文不详细地介绍WebSocket规范,主要介绍下WebSocket在Java Web中的实现。

二.WebSocket兼容性

WebSocket小插件

三.WebSocket应用场景

随着直播的兴起,以及现在社会发展的进步,更为重要的是浏览器的更新换代,世界互联网技术的发展。WebSocket应用会越来越广泛。下面是我近期写的一个WebSocket小插件,能够满足一般的需求。

现在为大家分享一下,多谢大家指正。

 //lk-2017-05-04
var _websocket ={
option:{
websocket:window.WebSocket || window.MozWebSocket,
websockets:'',
_websocket_des:'',
url:'',
},
init:function(url,send,message){
if(this.option.websocket){
window.onbeforeunload=function(){
_websocket.option._websocket_des.close();
}
this.option.url=url;
if(send && Object.prototype.toString.call(send)=="[object Function]") this.option.send=send;
if(message && Object.prototype.toString.call(message)=="[object Function]") this.option.message=message;
if(this.option.message && this.option.send){
return this.main(url,send,message);
}else if(this.option.message){
return this.main(url,false,message);
}else if(this.option.send){
return this.main(url,send,false);
}else{
return this.main(url);
} }else{
return '当前设备不支持'
}
},
doopen:function(){
console.log('链接open')
},
doclose:function(){
console.log('链接close');
_websocket.option._websocket_des.close();
},
doError:function(){
console.log('链接出错')
},
doMessage:function(message){
console.log('收到message='+message);
},
doSend:function(message){
if(this.readyState==1) {
this.send(JSON.stringify(message));
} else {
console.log("您已经掉线,无法与服务器通信!");
}
},
Reconnect:function(){
return _websocket.main(_websocket.option.url,_websocket.option.send,_websocket.option.message);
},
main:function(wcUrl,send,message){
this.option.websockets = new this.option.websocket(encodeURI(wcUrl));
this.option.websockets.onopen = this.doopen;//打开
this.option.websockets.onerror = this.doError;//出错
this.option.websockets.onclose = this.doclose;//关闭
this.option.websockets.onmessage = (message || this.doMessage);//接收
this.option.websockets.onSend= (send || this.doSend);//发送
this.option.websockets.Reconnect = this.Reconnect;//重新连接
this.option._websocket_des=this.option.websockets;
return this.option.websockets;
} }
 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>websocket-demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<style type="text/css">
#msges{
width: 220px;
height: 35px;
border: 1px solid #ccc;
border-radius: 5px;
text-indent: 10px;
}
#btn{
margin-left: 15px;
height: 35px;
width: 65px;
border: none;
background-color: rebeccapurple;
border-radius: 5px;
color: #fff;
}
#list{
background-color: #D1DBE5;
padding: 10px;
height: 300px;
overflow-y: auto;
}
p{
font-size: 25px;
width: 120px;
line-height: 50px;
padding: 0;
margin: 0;
}
</style>
</head>
<body onkeydown="keyLogin();">
<input type="text" id="msges" placeholder="请输入消息" /><input id="btn" type="button" onclick="webs.onSend()" value="发送" />
<p>消息列表</p>
<div id="list"> </div>
<script type="text/javascript" src="js/websocket.js" ></script>
<script>
var wurl='ws://192.168.109.53:8080/ssm/websocket';
var webs=_websocket.init(wurl,function(){ //console.log('send1') JSON.stringify(sends) if(webs.readyState==1) {
var sends=document.getElementById("msges").value;
webs.send(sends|| '你输入的是什么?');
document.getElementById("msges").value='';
}else{
console.log('已断开链接');
webs=webs.Reconnect();
} },function(msgges){
//console.log('msgges1');
document.getElementById("list").innerHTML+=msgges.data+ '<br/>';
}); function keyLogin(){
event.keyCode==13?webs.onSend():'';
}
</script>
</body>
</html>

效果如图:

WebSocket小插件

小伙伴们,这只是前端代码哦!!需要后端支持提供接口才可以长连接的。

websocket连接个数

Tomcat的WebSocket最大连接数为200。chrome最多连接256个。

总结:

websocket以后肯定是互联网发展的趋势,可实时显示数据,保证数据的准确性与后端的一致性。上边贴出的js代码不是最好的,如果一个页面链接一个 websocket足够您使用,如果一个页面需要链接多个 websocket,你还需要联系我或者你自己在重新封装。嘿嘿!