当前位置:网站首页>In order to make remote work unaffected, I wrote an internal chat room | community essay
In order to make remote work unaffected, I wrote an internal chat room | community essay
2022-06-30 16:46:00 【InfoQ】
// Start a socket Code ( client )
wx.connectSocket({
// Connect a socket
url:'wss://example.qq.com',
data:{},
header:{
'content-type':'application/json'
},
protocols:['protocol1'],
method:'GET'
})
wx.onSocketOpenwx.onSocketOpen(function(res){
console.log('WebSocket Connection is open !');
})
wx.sendSocketMessagewx.onSocketOpen(function(res){
wx.sendSocketMessage({
data:msg
})
})
wx.onSocketMessagewx.onSocketMessage(function(res){
console.log(' Received a message from the server :'+res.data)
})
wx.onSocketError(function(res){
console.log('websocket Connection open failed , Please check the system and network !');
})
wx.onSocketClose(function(res){
console.log('websocket Connection closed !');
})
npm install -g ws
const WebsocketServer=require('ws').Server;
let wbsocketServer=new WebsocketServer({
port:8081,
autoAcceptConnections:true
})
let clients=[]
let connectNum=0
// Listen for connections and messages
wbsocketServer.on('connection',(ws)=>{
clients.push(ws);
++connectNum;
console.log(' Number of connections :'+connectNum);
ws.on('message',(message)=>{
let objMessage=JSON.parse(message);
console.log(objMessage.data);
// You can do some processing or forward to other clients
})
// Send messages randomly
setInterval(()=>{
if(connectNum!==0){
setTimeout(()=>{
// Get the latest connections from the connection pool
clients[clients.length-1].send(JSON.stringify({data:' Messages from the server '}))
},Math.random()*1000*3)
}else{
console.log(' No client connection ')
}
},10000)
ws.on('close',()=>{
console.log(' The connection is disconnected ');
// Delete unwanted connections —— It's usually “ The oldest ” A piece of data
clients.pop();
--connectNum;
})
})
nodemon server.jsnpm install wepy-cli -g
wepy init standard chat
-- Created a chat project , After basic configuration , Enter this directory
npm i
-- Generate 、 Monitoring applet
wepy build -watch
// Turn on 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=" Please input chat content " bindinput="userSay" />
</view>
<button @tap="sendMessage" size="mini" class="btn"> Send a message </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'
// Monitors whether the status quantity is open
let socketOpen=false
export default class chat extends wepy.page{ //wepy Fixed format in
data={
say:'',
chats:[
{time:' Chat start ',text:''}
]
}
methods={
// User input related
userSay(e){
this.say=e.detail.value
this.$apply()
},
// Send conversation
sendMessage(){
let time=new Date()
this.chats=this.chats.concat([time:time.toLocaleTimeString(),text:' I said, :'+this.say])
this.handleSendMessage()
this.$apply()
}
}
// Start a socket
startSocket(){
wepy.connectSocket({
url:'ws://127.0.0.1:8081'
})
}
wssInit(){
const that=this
this.startSocket()
// Connection failure displays
wepy.onSocketError(function(res){
socketOpen=false
console.log('websocket Connection open failed , Please check !',res)
setTimeout(()=>{
that.startSocket()
},2000)
})
// Monitor connection successful
wepy.onSocketOpen(function(res){
socketOpen=true
console.log('websocket Connection is open ')
// Receiving messages from the server
that.receiveMessage()
})
}
receiveMessage(){
const that=this
if(socketOpen){
console.log(' Read socket The server ...')
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:' The server said :'+resData.data}])
that.$apply()
}
})
}else{
// The unopened state requires delayed reconnection
console.log(' The server is not connected ')
setTimeout(()=>{
that.receiveMessage()
},2000)
}
}
// Send a message
handleSendMessage(){
const that=this
wepy.sendSocketMessage({
data:JSON.stringify({data:that.say})
})
}
events={}
onLoad(){
const that=this
setTimeout(()=>{
that.wssInit()
},1000)
}
}
</script>
边栏推荐
- AVIC UAV technology innovation board is listed: the fist product with a market value of 38.5 billion is pterodactyl UAV
- 【Verilog基础】关于Clock信号的一些概念总结(clock setup/hold、clock tree、clock skew、clock latency、clock transition..)
- [Verilog basics] octal and hexadecimal representation of decimal negative numbers
- Wechat emoticons are written into the judgment, and the OK and bomb you send may become "testimony in court"
- 2022 Blue Bridge Cup group B -2022- (01 backpack to calculate the number of schemes)
- [unity ugui] scrollrect dynamically scales the grid size and automatically locates the middle grid
- [Verilog basics] summary of some concepts about clock signals (clock setup/hold, clock tree, clock skew, clock latency, clock transition..)
- MySQL master-slave configuration
- go-zero微服务实战系列(八、如何处理每秒上万次的下单请求)
- 中航无人机科创板上市:市值385亿 拳头产品是翼龙无人机
猜你喜欢
![[download attached] installation and use of penetration test artifact Nessus](/img/ef/b6a37497010a8320cf5a49a01c2dff.png)
[download attached] installation and use of penetration test artifact Nessus

备战数学建模33-灰色预测模型2

The inspiration from infant cognitive learning may be the key to the next generation of unsupervised machine learning

AVIC UAV technology innovation board is listed: the fist product with a market value of 38.5 billion is pterodactyl UAV

How cloudxr promotes the future development of XR

Tencent two sides: @bean and @component are used on the same class. What happens?

go-zero微服务实战系列(八、如何处理每秒上万次的下单请求)

ArcMap operation series: 80 plane to latitude and longitude 84

The new tea drinks are "dead and alive", but the suppliers are "full of pots and bowls"?

【微信小程序】常用组件基本使用(view/scroll-view/swiper、text/rich-text、button/image)
随机推荐
备战数学建模36-时间序列模型2
[bjdctf2020]the mystery of ip|[ciscn2019 southeast China division]web11|ssti injection
Installing jupyter notebook under Anaconda
Carry two load balancing notes and find them in the future
搬运两个负载均衡的笔记,日后省的找
Half year inventory of new consumption in 2022: the industry is cold, but these nine tracks still attract gold
[BJDCTF2020]The mystery of ip|[CISCN2019 华东南赛区]Web11|SSTI注入
附加:(还没写,别看~~~)CorsFilter过滤器;
Under the pressure of technology, you can quickly get started with eth smart contract development, which will take you into the ETH world
[Verilog basics] summary of some concepts about clock signals (clock setup/hold, clock tree, clock skew, clock latency, clock transition..)
【微信小程序】常用组件基本使用(view/scroll-view/swiper、text/rich-text、button/image)
Li Zexiang, a legendary Chinese professor, is making unicorns in batches
Interesting research on mouse pointer interaction
2022 Blue Bridge Cup group B -2022- (01 backpack to calculate the number of schemes)
几百行代码实现一个 JSON 解析器
更多龙蜥自研特性!生产可用的 Anolis OS 8.6 正式发布
What is the difference between real-time rendering and pre rendering
边缘计算平台如何助力物联网发展
GaussDB创新特性解读:Partial Result Cache,通过缓存中间结果对算子进行加速
Rongsheng biology rushes to the scientific innovation board: it plans to raise 1.25 billion yuan, with an annual revenue of 260million yuan