-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
53 lines (49 loc) · 1.57 KB
/
index.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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>基于NodeJs的websocket简易聊天 </h1>
<div id="app">
<input id="sendMsg" type="text"/>
<button id="submitBtn">发送</button>
</div>
</body>
<script type="text/javascript">
//在页面显示聊天内容
function showMessage(str,type){
var div=document.createElement("div");
div.innerHTML=str;
if (type=="enter"){
div.style.color="blue";
}else if(type=="leave"){
div.style.color="red";
}
document.body.appendChild(div);
}
//新建一个websocket
var websocket=new WebSocket("ws://localhost:3101");
//打开websocket连接
websocket.onopen=function(){
console.log('已经连上服务器----')
document.getElementById("submitBtn").onclick=function(){
var txt=document.getElementById("sendMsg").value;
if(txt){
//向服务器发送数据
websocket.send(txt);
}
}
}
//关闭连接
websocket.onclose=function(){
console.log("websocket close");
}
//接收服务器返回的数据
websocket.onmessage=function(e){
var mes=JSON.parse(e.data)
showMessage(mes.data,mes.type);
}
</script>
</html>