<template>
<view class="content">
<input class="uni-input" focus placeholder="自動獲得焦點" v-model="msg" style="padding-top: 100rpx;"/>
<image class="logo" src="/static/logo.png"></image>
<view class="text-area">
<text class="title">{{title}}</text>
</view>
<view class="">
<button type="default" @click="clickRequest()">發送</button>
</view>
</view>
</template>
<script>
let _this
export default {
data() {
return {
title: '文本聊天',
socketTask:null,
is_open_socket:false,
msg:'',
chatid:300,
}
},
onLoad() {
_this = this
},
onShow() {
// this.connectScoketInit()
},
beforeDestroy() {
// this.closeSocket()
},
methods: {
connectScoketInit(){
this.socketTask = uni.connectSocket({
url:"ws://192.168.31.99:8080/ws?uid=100&chatid="+_this.chatid,
success(data) {
console.log("websocket連結成功")
}
})
this.socketTask.onOpen((res)=>{
console.log("websocket連結正常打開在……");
this.is_open_socket=true;
this.socketTask.send({
data:"uni-app-01發送一條消息",
async successs(){
console.log("消息發送成功");
}
})
this.socketTask.onMessage(function(res){
console.log("收到伺服器内容:"+res.data);
_this.title=res.data
})
})
this.socketTask.onClose(function(){
console.log("已經關閉了")
})
},
closeSocket(){
this.socketTask.close({
success(res) {
this.is_open_socket=false
console.log("關閉成功------",res)
},
fail(err) {
console.log("關閉失敗",err)
}
})
},
clickRequest(){
if(this.is_open_socket){
this.socketTask.send({
data:"100,1,"+_this.msg,
async success(){
console.log("消息發送成功")
}
})
}
},
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>