<template>
	<view>
		<button type="primary" @tap="connect">连接</button>
		<!-- <button type="warn" @tap="print">打印</button> -->
	</view>
</template>

<script setup>
import { onMounted } from 'vue';

onMounted(() => {
	uni.onSocketOpen((res) => {
		console.log('连接成功', res)
		print()
		uni.showToast({
			title: '连接成功',
			icon: 'none'
		})
	})
	
	uni.onSocketError((error) => {
		console.log('连接错误', error)
		uni.showToast({
			title: '连接错误',
			icon: 'none'
		})
	})
	
	uni.onSocketClose((res) => {
		console.log('连接关闭', res)
		uni.showToast({
			title: '连接关闭',
			icon: 'none'
		})
	})
	
	uni.onSocketMessage((res) => {
		console.log('收到消息', res)
		uni.showToast({
			title: '收到消息',
			icon: 'none'
		})
	})
})

function connect() {
	uni.connectSocket({
		url: 'ws://192.168.1.200:9100',
		success() {
			uni.showToast({
				title: '连接成功',
				icon: 'none'
			})
		},
		fail(error) {
			console.log(error)
			uni.showToast({
				title: '连接失败',
				icon: 'none'
			})
		}
	})
}

function print () {
	uni.sendSocketMessage({
		// data: '<html><body><div>我就打印下，莫慌。。。。</div></body></html>',
		data: '我就打印下，莫慌。。。。',
		success() {
			uni.showToast({
				title: '发送成功',
				icon: 'none'
			})
		},
		fail(error) {
			console.log(error)
			uni.showToast({
				title: '发送失败',
				icon: 'none'
			})
		}	
	})
}
</script>

<style lang="scss">

</style>
