当前位置:网站首页>为了使远程工作不受影响,我写了一个内部的聊天室 | 社区征文
为了使远程工作不受影响,我写了一个内部的聊天室 | 社区征文
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>
边栏推荐
- Does flinkcdc have to be a clustered version if the monitored database is Mongo
- Unsupported major.minor version 52.0
- [time series database incluxdb] code example for configuring incluxdb+ data visualization and simple operation with C under Windows Environment
- 《网络是怎么样连接的》读书笔记 - 汇总篇
- MC Instruction Decoder
- Bidding announcement: remote disaster recovery project of Shenzhen Finance Bureau database
- Google play index table
- Table responsive layout tips for super nice
- [CVE-2019-0193] - Apache Solr DataImport 远程命令执行分析
- Policy Center > Device and Network Abuse
猜你喜欢

牛客网:有多少个不同的二叉搜索树

优惠券种类那么多,先区分清楚再薅羊毛!

topic: Privacy, Deception and Device Abuse

【活动报名】探秘元宇宙,就差你了!7月2号我在深圳现场等你!
Mysql8.0 method and steps for enabling remote connection permission
![[download attached] installation and use of penetration test artifact Nessus](/img/ef/b6a37497010a8320cf5a49a01c2dff.png)
[download attached] installation and use of penetration test artifact Nessus
![[unity ugui] scrollrect dynamically scales the grid size and automatically locates the middle grid](/img/c9/ff22a30a638b5d9743d39e22ead647.png)
[unity ugui] scrollrect dynamically scales the grid size and automatically locates the middle grid

云化XR,如何助力产业升级

I implement "stack" with C I

Cesium-1.72 learning (add points, lines, cubes, etc.)
随机推荐
After 15 years of working on 21 types of hardware, where is Google?
备战数学建模36-时间序列模型2
药品管理系统加数据库,一夜做完,加报告
[CVE-2019-0193] - Apache Solr DataImport 远程命令执行分析
Half year inventory of new consumption in 2022: the industry is cold, but these nine tracks still attract gold
The inspiration from infant cognitive learning may be the key to the next generation of unsupervised machine learning
招标公告:2022年台州联通Oracle一体机和数据库维保服务项目
[time series database incluxdb] code example for configuring incluxdb+ data visualization and simple operation with C under Windows Environment
备战数学建模35-时间序列预测模型
Unsupported major. minor version 52.0
招标公告:深圳市财政局数据库异地灾备项目
优惠券种类那么多,先区分清楚再薅羊毛!
RT-Thread 堆区大小设置
Implementation of Devops in the core field of qunar, the Internet R & D Efficiency
RT thread heap size Setting
2022蓝桥杯国赛B组-费用报销-(线性dp|状态dp)
有意思的鼠标指针交互探究
Cesium-1.72 learning (earth model creation online offline tile)
【机器学习】K-means聚类分析
附加:(还没写,别看~~~)CorsFilter过滤器;