ZBLOG

vue中怎么创建WebSocket连接,并发送和接收消息

在Vue中创建WebSocket连接和发送接收消息需要完成以下几个步骤:

  1. 创建WebSocket实例

在Vue组件的created()或mounted()生命周期方法中创建WebSocket实例并打开连接。例如:

  1. export default {
  2. name: 'MyComponent',
  3. data() {
  4. return {
  5. socket: null,
  6. message: ''
  7. }
  8. },
  9. created() {
  10. this.socket = new WebSocket('ws://localhost:8080/ws')
  11. this.socket.onopen = () => {
  12. console.log('Connected to WebSocket server.')
  13. }
  14. this.socket.onmessage = (event) => {
  15. console.log('Received message: ' + event.data)
  16. }
  17. }
  18. }
  1. 发送消息

使用WebSocket实例的send()方法发送消息。例如:

  1. methods: {
  2. sendMessage() {
  3. this.socket.send(this.message)
  4. this.message = ''
  5. }
  6. }
  1. 关闭连接

在Vue组件的beforeDestroy()生命周期方法中关闭WebSocket连接。例如:

  1. beforeDestroy() {
  2. if (this.socket !== null && this.socket.readyState === WebSocket.OPEN) {
  3. this.socket.close()
  4. }
  5. }

这样,在Vue中就可以使用WebSocket实现实时通信了。需要注意的是,由于WebSocket在跨域访问时需要服务器端设置CORS(Cross-Origin Resource Sharing),因此建议将WebSocket连接地址设置为相对路径或与前端页面同域名的绝对路径。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=1222

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?