基于H5的webSocket通信
这里主要以一个简单例子来做说明
创建一个主服务器
1、创建一个主服务器
主服务器创建逻辑过程
/*
1.通过ws模块来创建服务器
2.服务器连接客户端---(给客户端编号)
3.接收客户端发来的信息
4.监听客户端下线
*/
//1.通过ws模块,来创建服务器
const webSocket = require('ws');//安装并引入webSocket模块
const ws = new webSocket.server({
port:3000,
hostname:'10.31.161.48';
});
//2.服务器连接客户端并对客户端数量计数
var clients = {};
var count = 0;
ws.on('connection',client=>{
client.name=++count;//对客户端进行编号
clients[client.name]=client;//将连接到客户端存到集合内
//3.接收客户端发来的数据
client.on('message',msg=>{
console.log(`客户端${client.name}:${msg}}`);
boardcast(client,msg);//接收到客户信息时,调用函数显示所有信息
});
//4.监听客户端下线
client.on('close',()=>{
delete clients[client.name];//清除下线客户端
console.log(`客户端${client.name}closed~~~`)
});
//对客户端发来数据进行封装调用
function boardcast(client,msg){
for (var key in clients){
clients[key].send(msg);//接收到客户端信息,便利客户端,显示所有信息
}
}
创建客户端
2、创建一个客户端
//使用h5提供的一个Socket 全局对象 进行客户端创建
const ws= new WebSocket('ws://10.31.161.48:3000');
ws.onopen=()=>{
// 打开WebSocket连接后立刻发送一条消息:
ws.send('欢迎来到xxx直播间');
};
ws.onmessage=(msg)=>{
//获取所有信息展示在客户端
};
//客户端监控异常信息
ws.onerror=(error)=>{
if(error){
console.log(error)
}
};
ws.onclose=()=>{
console.log(`下线了`);
}
创建一个静态服务器
3、创建一个静态服务器,用来展示客户端页面信息
const express = require('express');
const app = express();
const path = require('path');
const hostname='10.31.161.48';
const port= 2000;
//设置一个静态文件夹client,让我们的服务器找到文件client/index.html
app.use(express.static(path.jion(__dirname,'client') ) );
//监听服务器
app.listen(port,hostname,()=>{
console.log(`The web server is running at:http//${hostname}:${port}`)
});
4、H5页面操作
//页面布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>WebSocket</title>
<style>
.con{
overflow: hidden;
width: 850px;
border: rebeccapurple 2px solid;
}
.lt{
width: 400px;
height:500px;
float: left;
}
img{
width:100%;
height:100%;
}
.rt{
width: 400px;
height:500px;
float: right;
/* margin-left:40px; */
border-left: rebeccapurple 2px solid;
}
#content{
overflow-y: scroll;
width: 400px;
height: 300px;
/* border: solid 1px #000 */
}
.box{
height: 50px;
background: burlywood;
}
#msg{
width: 400px;
height: 50px;
border: 0;
}
#submit{
position:absolute;
right:10px;
bottom:-50px;
width: 80px;
height: 30px;
background: greenyellow;
}
</style>
<script src="wsClient.js" charset="utf-8"></script>
</head>
<body>
<div class="con">
<div class="lt"><img src="./img/1.jpg"></div>
<div class="rt">
<div id="content" name="name"></div>
<br />
<div>
<div style="position: relative;">
<div class="box"></div>
<input type="text" id="msg">
<button id="submit">发送</button>
</div>
</div>
</div>
</body>
</html>
html页面布局极为简单,大家可以根据自己的方式添加,让布局更美观
//内容请求发送
<script>
var msg = document.querySelector('#msg');
var submit = document.querySelector('#submit');
submint.onclick=function()
var val=msg.value;
ws.send(val)//将书写内容发送到服务端,并通过客户端显示
msg.value='';//发送以后清空发送框,等待再次输入
}
</script>