当前位置:网站首页>为了使远程工作不受影响,我写了一个内部的聊天室 | 社区征文
为了使远程工作不受影响,我写了一个内部的聊天室 | 社区征文
2022-06-30 15:47:00 【InfoQ】
//启动一个socket代码(客户端)
wx.connectSocket({
//连接一个socket
url:'wss://example.qq.com',
data:{},
header:{
'content-type':'application/json'
},
protocols:['protocol1'],
method:'GET'
})
wx.onSocketOpenwx.onSocketOpen(function(res){
console.log('WebSocket连接已打开!');
})
wx.sendSocketMessagewx.onSocketOpen(function(res){
wx.sendSocketMessage({
data:msg
})
})
wx.onSocketMessagewx.onSocketMessage(function(res){
console.log('收到服务器的消息:'+res.data)
})
wx.onSocketError(function(res){
console.log('websocket连接打开失败,请检查系统及网络!');
})
wx.onSocketClose(function(res){
console.log('websocket连接已关闭!');
})
npm install -g ws
const WebsocketServer=require('ws').Server;
let wbsocketServer=new WebsocketServer({
port:8081,
autoAcceptConnections:true
})
let clients=[]
let connectNum=0
//监听连接和消息
wbsocketServer.on('connection',(ws)=>{
clients.push(ws);
++connectNum;
console.log('连接的数量:'+connectNum);
ws.on('message',(message)=>{
let objMessage=JSON.parse(message);
console.log(objMessage.data);
//可以做一些处理或者转发其它客户端
})
//随机发送消息
setInterval(()=>{
if(connectNum!==0){
setTimeout(()=>{
//从连接池中获取最新连接
clients[clients.length-1].send(JSON.stringify({data:'来自服务器的消息'}))
},Math.random()*1000*3)
}else{
console.log('无客户端连接')
}
},10000)
ws.on('close',()=>{
console.log('有连接断开');
//删除不需要的连接——一般是“最老的”一条数据
clients.pop();
--connectNum;
})
})
nodemon server.jsnpm install wepy-cli -g
wepy init standard chat
--创建了一个chat项目,完成基本配置后,进入该目录
npm i
--生成、监控小程序
wepy build -watch
//开启promisify
constructor{
super();
this.use('requestfix');
this.use('promisify');
}
pages:[
'pages/chat'
],
<block></block><repeat></repeat><template>
<view class="page">
<view class="chats">
<repeat for="{{chats}}" item="item">
<view style="font-size:20rpx;color:#ababab">{{item.item}}</view>
<view style="font-size:25rpx;padding-bottom:20rpx;">{{item.text}}</view>
</repeat>
</view>
<view class="chatInput">
<input placeholder="请输入聊天内容" bindinput="userSay" />
</view>
<button @tap="sendMessage" size="mini" class="btn">发送消息</button>
</view>
</template>
<style lang="less">
.page{
position:fixed;
height:100vh;
width:100vw;
background:#e8e9d2;
}
.chats{
text-align:center;
margin:10vh 10vh 10vw 10vw;
height:65vh;
width:80vw;
background-color:aliceblue;
overflow:auto;
}
.chatInput{
background:aliceblue;
height:40rpx;
font-size:20rpx;
padding:10rpx;
width:70vw;
margin-left:15vw;
border-radius:20rpx;
margin-bottom:3vh;
}
.btn{
width:70vw;
mnargin-left:15vw;
}
</style>
<script>
import wepy from 'wepy'
//监听是否打开的状态量
let socketOpen=false
export default class chat extends wepy.page{ //wepy中的固定格式
data={
say:'',
chats:[
{time:'聊天开始',text:''}
]
}
methods={
//用户输入相关
userSay(e){
this.say=e.detail.value
this.$apply()
},
//发送对话
sendMessage(){
let time=new Date()
this.chats=this.chats.concat([time:time.toLocaleTimeString(),text:'我说:'+this.say])
this.handleSendMessage()
this.$apply()
}
}
//启动一个socket
startSocket(){
wepy.connectSocket({
url:'ws://127.0.0.1:8081'
})
}
wssInit(){
const that=this
this.startSocket()
//连接失败显示
wepy.onSocketError(function(res){
socketOpen=false
console.log('websocket连接打开失败,请检查!',res)
setTimeout(()=>{
that.startSocket()
},2000)
})
//监听连接成功
wepy.onSocketOpen(function(res){
socketOpen=true
console.log('websocket连接已打开')
//接收服务器的消息
that.receiveMessage()
})
}
receiveMessage(){
const that=this
if(socketOpen){
console.log('读取socket服务器...')
wepy.onSocketMessage(function(res){
let time=new Date()
let resData=JSON.parse(res.data)
if(resData.data){
that.chats=that.chats.concat([{time:time.toLocaleTimeString(),text:'服务器说:'+resData.data}])
that.$apply()
}
})
}else{
//未打开状态需要延时重新连接
console.log('服务器没有连接上')
setTimeout(()=>{
that.receiveMessage()
},2000)
}
}
//发送消息
handleSendMessage(){
const that=this
wepy.sendSocketMessage({
data:JSON.stringify({data:that.say})
})
}
events={}
onLoad(){
const that=this
setTimeout(()=>{
that.wssInit()
},1000)
}
}
</script>
边栏推荐
- 荣盛生物冲刺科创板:拟募资12.5亿 年营收2.6亿
- Google play index table
- [BJDCTF2020]The mystery of ip|[CISCN2019 华东南赛区]Web11|SSTI注入
- RT thread heap size Setting
- MySQL proxy middleware atlas installation and configuration
- Finally understand science! 200 pictures to appreciate the peak of human wisdom
- IIS无法加载字体文件(*.woff,*.svg)的解决办法
- 云和恩墨中标天津滨海农村商业银行2022-2023年度Oracle维保项目
- Implementation of Devops in the core field of qunar, the Internet R & D Efficiency
- 超 Nice 的表格响应式布局小技巧
猜你喜欢

荣盛生物冲刺科创板:拟募资12.5亿 年营收2.6亿

几百行代码实现一个 JSON 解析器

“低代码”在企业数字化转型中扮演着什么角色?

Cesium-1.72 learning (deploy offline resources)

How the edge computing platform helps the development of the Internet of things

15年做糊21款硬件,谷歌到底栽在哪儿?

KDD 2022 | how far are we from the general pre training recommendation model? Universal sequence representation learning model unisrec for recommender system

19:00 p.m. tonight, knowledge empowerment phase 2 live broadcast - control panel interface design of openharmony smart home project
mysql8报错:ERROR 1410 (42000): You are not allowed to create a user with GRANT解决办法

Cesium-1.72 learning (add points, lines, cubes, etc.)
随机推荐
go-zero微服务实战系列(八、如何处理每秒上万次的下单请求)
服务端测试工程师面试经验
构建适合组织的云原生可观测性能力
Siyuan notes: can you provide shortcut keys for folding all titles on the page?
MySQL开放远程连接权限的两种方法
Headhunter 50, 000, I'll go to VC
[algorithm] after summarizing the four linked lists, I brushed two interview questions
IIS无法加载字体文件(*.woff,*.svg)的解决办法
flink sql cdc 同步sqlserver 报错什么原因啊
优惠券种类那么多,先区分清楚再薅羊毛!
Under the pressure of technology, you can quickly get started with eth smart contract development, which will take you into the ETH world
Interpretation of gaussdb's innovative features: partial result cache accelerates operators by caching intermediate results
GaussDB创新特性解读:Partial Result Cache,通过缓存中间结果对算子进行加速
Asp. NETCORE uses cache and AOP to prevent repeated commit
Types of waveguides
云和恩墨中标天津滨海农村商业银行2022-2023年度Oracle维保项目
I 用c I 实现“栈”
[unity ugui] scrollrect dynamically scales the grid size and automatically locates the middle grid
抖快B为啥做不好综艺
备战数学建模36-时间序列模型2