-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.html
70 lines (63 loc) · 2 KB
/
client.html
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
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>WebSocket Echo Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<style>
#box{ border:1px solid #999; height:600px; width:700px; overflow-y:scroll;}
</style>
<script>
var id=1;//聊天室id
var uid=localStorage.uid;
var ws = new WebSocket("ws://localhost:8181");
ws.onopen = function(e){
var otext={'id':id,'uid':uid};
var string = JSON.stringify(otext)
ws.send(string);
console.log('连接到服务器打开');
}
ws.onmessage=function(evt){
var data =eval('('+evt.data+')');//转对象
console.log(data);
var state=data['state'];
if(state==1){
localStorage.uid=data['uid'];
return false;
}
var text=data['msg'];
var textnode=document.createElement('div');
textnode.innerHTML=text;
var box=document.getElementById('box');
box.appendChild(textnode);
console.log("数据已接收...");
}
ws.onclose = function(){
console.log("连接已关闭...");
};
function sendMessage() {
var text=document.getElementById('message').value;
var otext={'id':id,'text':text,'uid':uid};
var string = JSON.stringify(otext)
console.log('发送成功:'+string);
ws.send(string);
}
</script>
</head>
<body >
<div class="vertical-center">
<div class="container">
<p id="box"></p>
<form role="form" id="chat_form" onsubmit="sendMessage(); return false;">
<div class="form-group">
<input class="form-control" type="text" name="message" id="message"
placeholder="发送消息" value="" />
</div>
<button type="button" id="send" class="btn btn-primary"
onclick="sendMessage();">
发送
</button>
</form>
</div>
</div>
</body>
</html>