<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>