vue中使用websocket

本文介绍如何在Vue.js项目中使用WebSocket进行实时双向通信,包括初始化WebSocket连接、监听不同事件并处理错误,以及如何从客户端发送消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

websocket基础

<template>
	<div class="websocket">
		<input type="text" placeholder="输入消息" v-model="value">
		<button @click="send">发送</button>
		<div class="message">{{message}}</div>
	</div>
</template>

<script>
export default {
  name: 'websocket',
  data(){
	  return {
		  socket: '',
		  value: '',
		  message: ''
	  }
  },
  mounted() {
	//WebSocket
	this.initWebsocket();
  },
  methods:{
	  //初始化websocket
	  initWebsocket(){
		  //判断浏览器是否支持WebSocket
		  if ("WebSocket" in window){
		  	console.log("您的浏览器支持 WebSocket!");
		  	// 打开一个 web socket
		    this.socket = new WebSocket("ws://echo.websocket.org");
			this.socket.onopen = this.socketOnopen;
		  	this.socket.onmessage = this.socketOnmessage;
			this.socket.onerror = this.socketOnerror;
			this.socket.onclose = this.socketOnclose;
		  }else{
		  	alert("您的浏览器不支持 WebSocket!");
		  }
	  },
	  //连接建立时触发
	  socketOnopen(){
		console.log('链接成功')
	  },
	  //客户端接收服务端数据时触发
	  socketOnmessage(e){
	  	console.log(e)
		this.message = e.data
	  },
	  //通信发生错误时触发
	  socketOnerror(){
	  		  
	  },
	  //连接关闭时触发
	  socketOnclose(){
	  		  
	  },
	  //点击发送
	  send(){
		  this.socket.send(this.value)
	  }
  }
}
</script>

<style>
.message{
	width: 500px;
	height: 31.25rem;
	border: 1px solid #000;
}
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YangYun_Coder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值