-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.htm
93 lines (92 loc) · 2.46 KB
/
test.htm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<meta charset='utf-8' />
<style>
div{
border:1px solid #ccc;box-shadow:0 0 10px #000;
}
#result{
clear: both;
position: relative;
margin: 10px;
top: 10px;
border: none;
border-top: 2px dashed #ccc;
overflow: scroll;
height: 90%;
padding: 13px;
box-shadow: 0 0 0 #f00;
background:#eee;
}
button{
float:left;margin-top:10px;margin-left:10px;width:100px;height:30px;
}
</style>
<div>
<button onclick='sendMessage()'>发送消息</button>
<div id='result'></div>
</div>
<script>
var r=0,rnd=function(){
return Math.random()+(r++);
};
var queue=[];//消息队列,以保证一个消息的发送是不可分割的
var ws=new WebSocket('ws://127.0.0.1:8100');
ws.onclose=function(e){log('closed: '+e.reason)};
ws.onopen=function(){
var message;
setInterval(function(){
//普通消息
message=new msg;
message.create({boundary:rnd()},true);
message.appendMsgBody(JSON.stringify({
point:[2334,34324],
msg:'test',
lng_lat:[23.234,432.23]
}));
queue.push(message);
//超短消息
message=new msg;
message.create({nodata:true});
queue.push(message);
//二进制消息
message=new msg;
message.create({boundary:rnd()});
message.appendMsgBody(new Blob(['hello'],{type:'image/jpeg'}));
message.appendMsgBody(new Blob(['world'],{type:'image/jpeg'}));
queue.push(message);
},2000);
};
ws.onmessage=function(e){log(e.data)};
log=function(e){result.insertAdjacentHTML('afterBegin',e+'<br/>')};
setInterval(function(){
if(queue.length){
queue.shift().send(ws);
}
},100);
function sendMessage(){
var message=new msg;
message.create({boundary:rnd()});
message.appendMsgBody('发送一个测试消息');
message.appendMsgBody('附加更多消息内容,使用\n换行');
queue.push(message);
}
var msg=function(){};
//如果需要回复,这发送的头部会带上--k 随机字符串,接收的回复会包含--r 这个随机字符串
msg.prototype.create=function(option,needReply){
this.data=[];
if(needReply)this.data.push('--k '+Math.random());
for(var what in option){
this.data.push('--'+what.charAt(0)+(option[what]?' ':'')+option[what]);
if(what==='boundary')this.boundary=option[what];
}
this.data=[this.data.join('\n')];
};
msg.prototype.appendMsgBody=function(what){this.data.push(what);};
msg.prototype.send=function(socket){
if(this.boundary)this.data.push(this.boundary+'--');
this.data.every(function(what){
socket.send(what);
return true;
});
delete this.data;
};
</script>