uniapp通过WebSocket与设备通讯

260 阅读1分钟
	<view class="content">
		<button @click="open()">连接</button>
		<button @click="sendMessage('11')">发送</button>
		<button @click="closeSocket()">关闭</button>
		<button @click="message=[]">清除数据</button>
		<view class="data">
			<view v-for="(e,i) in message" :key="i">{{e}}</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isLogin: false,
				url: 'ws://192.168.4.1:9988',
				ST: false,
				isOpen: false,
				timer: null,
				message: []
			}
		},
		onLoad() {
			this.open()
		},
		methods: {
			open() {
				this.closeSocket();
				this.ST = uni.connectSocket({
					url: this.url,
					complete: (e) => {},
					fail: (f) => {
						console.log(f);
					},
					success: (s) => {
						console.log(this.ST);
						if (!this.ST) {
							console.log(this.ST);
							return //防止错误open
						}
						uni.onSocketOpen((res) => {
							console.log('WebSocket连接已打开!');
							this.isLogin = true
							console.log('连接成功');
						});

						uni.onSocketMessage((res) => {
							console.log('接收到服务端发送的消息', res.data);
							this.message.push(res.data);
						})
						uni.onSocketOpen(function(res) {
							console.log('WebSocket连接已打开!');
						});
						uni.onSocketClose((res) => {
							console.log(res);
							if (!this.ST) {
								return;
							}
							uni.showToast({
								title: '与服务器连接中断,请重新刷新页面!',
								icon: 'loading'
							})
							clearInterval(this.t1);
							this.isLogin = false
							this.ST = false;
							this.timer = setTimeout(() => {
								this.open()
							}, 5000)
						});
						uni.onSocketError((res) => {
							if (!this.ST) {
								return;
							}
							uni.showToast({
								title: '与服务器连接错误,请重新刷新页面!',
								icon: 'loading'
							})
							this.isLogin = false
							this.ST = false
							this.timer = setTimeout(() => {
								this.open()
							}, 5000)
						});
					}
				});
			},
			//发送消息
			sendMessage(msg) {
				uni.sendSocketMessage({
					data: msg,
					success(res) {
						console.log(res);
						console.log('消息发送成功!')
					},
					fail(err) {
						console.log(err);
						console.log('消息发送失败!')
					}
				})
			},
			//关闭连接
			closeSocket() {
				//关闭socket连接
				this.ST = false;
				clearTimeout(this.timer);
				uni.closeSocket({
					success(res) {
						this.is_open_socket = false;
						console.log("关闭成功", res)
					},
					fail(err) {
						console.log("关闭失败", err)
					}
				});
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	button {
		margin: 10rpx 0;
	}

	.data {
		border: 1rpx solid #000;
		width: 90%;
		padding: 10rpx;
		margin: 10rpx auto;
		box-sizing: border-box;

		view {
			padding: 10rpx;
		}
	}
</style>

客户端与服务端必须连接同一个wifi