websocket学习

websocket的学习

公司自研了一个项目,需要使用到即时通讯,虽然任务最后没有落实到我手上,但是我还是去看了一下下,学会了一些基本的操作

websocket涉及到一些计算机网络相关的知识,此处省略一万字……

npm install nodejs-websocket

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
// node服务端代码结构
var ws = require("nodejs-websocket")
// 创建链接通道数组
const conList = []
var server = ws.createServer(function (conn) {
console.log('conn',conn)
// 将连接通道添加到数组中保存
conList.push(conn)
console.log("创建了一个websocket服务器",'有' + conList.length + '人连接上了')
conn.on("text", function (str) {
console.log("服务器接收到的数据是"+str)
// 循环遍历发送数据
for(var i = 0 ; i < conList.length; i++){
conList[i].sendText(str.toUpperCase()+"!!!")
}
})
conn.on("close", function (code, reason) {
console.log("websocket服务器关闭",'原因是' + reason)
// 如果某一个连接关闭 那么需要将其conList中删除
conList.splice(conList.indexOf(conn),1)
console.log('当前连接数量' + conList.length)
})
conn.on('error',function(code,reason){
console.log('异常事件',code,'原因是' + reason)
})
}).listen(8001,()=>{
console.log('running')
})
// nodemon app.js在8001端口启动一个websocket的服务

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style lang="">
div {
width: 200px;
height: 200px;
border: 1px solid black;
}
</style>
</head>
<body>
<input type="text">
<button>发送</button>
<ul>
消息列表:
</ul>
<script>
const ws = new WebSocket('ws://localhost:8001')
const btn = document.querySelector('button')
const ipt = document.querySelector('input')
const box = document.querySelector('ul')
// ws.addEventListener('open',()=>{

// })
btn.addEventListener('click',()=>{
let value = ipt.value
ws.send(value)
})
ws.addEventListener('message',(e)=>{
console.log('客户端接收到的消息是',e.data)
let li = document.createElement('li')
li.innerText = e.data
box.appendChild(li)
})
</script>
</body>
</html>

一个小的test就完成了…

后面想弄一个基于uniapp的websocket小程序,或许是五百年以后……