当前位置:网站首页>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>
边栏推荐
- Installing jupyter notebook under Anaconda
- MC Instruction Decoder
- Niuke.com: minimum cost of climbing stairs
- 如何得到股票开户的优惠活动?在线开户安全么?
- 2022蓝桥杯国赛B组-2022-(01背包求方案数)
- RT thread heap size setting
- 容联云首发基于统信UOS的Rphone,打造国产化联络中心新生态
- [Verilog basics] octal and hexadecimal representation of decimal negative numbers
- 牛客网:乘积为正数的最长连续子数组
- Bidding announcement: remote disaster recovery project of Shenzhen Finance Bureau database
猜你喜欢

【Verilog基础】关于Clock信号的一些概念总结(clock setup/hold、clock tree、clock skew、clock latency、clock transition..)

'&lt;', Hexadecimal value 0x3c, is an invalid problem solving
Two methods for MySQL to open remote connection permission
![[bjdctf2020]the mystery of ip|[ciscn2019 southeast China division]web11|ssti injection](/img/c2/d6760826b81589781574aebff61f9a.png)
[bjdctf2020]the mystery of ip|[ciscn2019 southeast China division]web11|ssti injection

Hundreds of lines of code to implement a JSON parser

今晚19:00知识赋能第2期直播丨OpenHarmony智能家居项目之控制面板界面设计

The image variables in the Halcon variable window are not displayed, and it is useless to restart the software and the computer

JS ES5也可以创建常量?

BC1.2 PD协议

Rong Lianyun launched rphone based on Tongxin UOS to create a new ecology of localization contact center
随机推荐
AVIC UAV technology innovation board is listed: the fist product with a market value of 38.5 billion is pterodactyl UAV
Compulsory national standard for electronic cigarette GB 41700-2022 issued and implemented on October 1, 2022
华为帐号多端协同,打造美好互联生活
数据挖掘知识点整理(期末复习版)
2020蓝桥杯国赛B组-搬砖-(贪心排序+01背包)
halcon知识:矩阵专题【02】
IndexSearch
Niuke network: longest continuous subarray with positive product
今晚19:00知识赋能第2期直播丨OpenHarmony智能家居项目之控制面板界面设计
Additional: (not written yet, don't look at ~ ~ ~) corsfilter filter;
Yunhe enmo won the bid for Oracle maintenance project of Tianjin Binhai rural commercial bank in 2022-2023
Bidding announcement: remote disaster recovery project of Shenzhen Finance Bureau database
Raft介绍
Mathematical modeling for war preparation 35 time series prediction model
ArcMap operation series: 80 plane to latitude and longitude 84
What is XR extended reality and what are the XR cloud streaming platforms
Bidding announcement: Taizhou Unicom Oracle all in one machine and database maintenance service project in 2022
Tencent two sides: @bean and @component are used on the same class. What happens?
halcon知识:区域专题【07】
RT thread heap size setting