//浏览器WebSocket对象
var wsImpl = window.WebSocket || window.MozWebSocket;
function SocketStart(options, cl) {
this.url = options.url;//Socket地址
this.ws = new wsImpl(options.url);//初始化Socket对象
this.userid = options.userid;//用户id
this.onmessage = options.onmessage;//接受消息回调函数
this.onopen = options.onopen;//连接成功回调函数
this.onclose = options.onclose;//连接断开回调函数
this.dataType = options.dataType || 'json';//json或txt格式数据 默认json
var _self = this;
SocketInit(_self)
}
function SocketInit(_self) {
//setTimeout
var loopTime;
/**
* 发送消息方法
* msg 消息内容,字符串或json都可以
* touser 接受方id
*/
_self.send = function (msg,touser) {
// 组装消息
var msg = {
userid: _self.userid,
touser:touser,
msg: msg
}
//转字符串
var msgstr=JSON.stringify(msg);
//获取消息字符串字节长度
var msglength=msgstr.StrLength();
//判断是否超过限制
if(msglength>4000){
console.error("消息内容过长!");
return;
}
// 发送消息
try {
_self.ws.send(msgstr);
} catch (error) {
console.log(error)
}
}
/**
* 接收消息事件
*/
_self.ws.onmessage = function (evt) {
// 判断消息是否为空
if (!evt.data) {
return;
}
//判断消息类型
var get_data;
if (_self.dataType == 'json') {
get_data = JSON.parse(evt.data)
} else {
get_data = evt.data
}
//判断消息是否为心跳
if (get_data.msg == '__loop__') {
return;
}
// 连接成功
if (get_data.msg == "__success__") {
console.log("连接成功!");
return;
}
//调用回调函数
if (_self.onmessage) {
_self.onmessage(get_data.msg,get_data.userid,get_data);
}
};
//连接成功事件
_self.ws.onopen = function () {
// 调用心跳函数 第一次发送内容为 __success__
loop("__success__");
//调用回调函数
if (_self.onopen) {
_self.onopen();
}
};
//断开连接事件
_self.ws.onclose = function () {
clearTimeout(loopTime);
console.error("连接断开!");
console.log("重新连接!");
//调用回调函数
if (_self.onclose) {
_self.onclose();
}
//1秒后重连
setTimeout(function () {
_self.ws = new wsImpl(_self.url);
SocketInit(_self)
}, 1000);
}
//心跳函数 递归执行 10秒一次,接收方为自己
function loop(i) {
_self.send((i || "__loop__"),_self.userid);
loopTime = setTimeout(function () {
loop();
}, 10000);
}
}
/**
* 获取字符串字节长度
*/
function StrLength(){
var num=0;
for (var i = 0; i < this.length; i++) {
var charCode=this[i].charCodeAt(0);
if (charCode < 0x007f) {
num++;
}
else if ((0x0080 <= charCode) && (charCode <= 0x07ff)) {
num+=2;
}
else if ((0x0800 <= charCode) && (charCode <= 0xffff)) {
num+=3;
}else{
num+=4;
}
}
return num;
}
/**
* 获取字符串字节长度
*/
String.prototype.StrLength=StrLength;
使用
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<span id="userid">
</span>
<br>
<input type="text" name="" id="touser" placeholder="接收方id">
<br>
<button id="send">发送消息</button>
<br>
<textarea id="msg" name="" id="" cols="60" rows="20" placeholder="消息内容"></textarea>
<br>
<textarea id="getmsg" name="" id="" cols="60" rows="20" placeholder="接收消息"></textarea>
<pre id="incomming"></pre>
<script src="jquery-3.4.1.min.js"></script>
<script src="SocketStart.js"></script>
<script type="text/javascript">
$(function () {
var userid = "aa" + Math.ceil(Math.random() * 100000);
$("#userid").text(userid)
var ss = new SocketStart({
url: "ws://localhost/Socket",
userid: userid,
onopen: function () {
console.log(666);
},
onclose: function () {
console.error(666);
},
onmessage: function (msg, userid,get_data) {
console.log(msg)//收到的消息内容
console.log(userid)//发送者的id
console.log(get_data)//接收到的完整数据
$("#getmsg").val(msg)
},
});
//发送消息
$("#send").click(function (e) {
ss.send($("#msg").val(), $("#touser").val())
});
})
</script>
</body>
</html>