首页 > 其他分享 >从零玩转Websocket实时通讯服务之前后端分离版本-websocket

从零玩转Websocket实时通讯服务之前后端分离版本-websocket

时间:2023-05-19 11:55:41浏览次数:37  
标签:websocket String param session 玩转 import Websocket public

title: 从零玩转Websocket实时通讯服务之前后端分离版本
date: 2021-10-25 00:47:12.945
updated: 2021-12-26 17:43:10.496
url: https://www.yby6.com/archives/websocket
categories: 
- OSS
- mysql
- api
- 单例模式
- websokcet
tags: 

前言

公司项目需要用到消息提示,那么WebSocket它来了经过我面向百度的学习,废话不多说直接开干.

后端搭建

一、依赖导入

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

二、搭建websocket服务

1.WebSocketConfig配置文件
/*==============================================================================
 = - Yang Buyi  Copyright (c) 2021 https://yangbuyi.top.
 =============================================================================*/

package top.yangbuyi.service_websocket.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;


/**
 * 配置文件
 *
 * @author Yang Buyi
 * @date 2021/10/25
 */
@Configuration
public class WebSocketConfig {


	/**
	 * 给Spring容器注入 ServerEndpointExporter 对象
	 *
	 * @return {@link ServerEndpointExporter}
	 */
	@Bean
	public ServerEndpointExporter serverEndpointExporter() {
		return new ServerEndpointExporter();
	}
}
2.WebSocketServer服务
/*==============================================================================
 = - Yang Buyi  Copyright (c) 2021 https://yangbuyi.top.
 =============================================================================*/

package top.yangbuyi.service_websocket.server;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * websocket前端请求服务地址
 *
 * /service_websocket/wspoint/yangbuyi
 *
 * @author Yang Buyi
 * @date 2021/10/25
 */
@ServerEndpoint("/service_websocket/wspoint/{loginName}")
@Component
public class WebSocketServer {

    /**
     * 存储每一个连接
     */
    private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 会话
     */
    private Session session;

    /**
     * 登录名
     */
    private String loginName = "";


    /**
     * 在开放
     *
     * @param session   会话
     * @param loginName 登录名
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("loginName") String loginName) {
        // 前端连接得到登陆名称
        this.loginName = loginName;
        // 当前websokcet生成的会话
        this.session = session;
        webSocketSet.add(this);
        try {
            sendMessage("success");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    /**
     * 在关闭
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
    }


    /**
     * 在消息
     *
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("接收到来自[" + message + "]发送的消息" + session);
        // 发送消息
//        for (WebSocketServer item : webSocketSet) {
//            try {
//                item.sendMessage(message + ",时间:" + new Date() + session);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
    }

    /**
     * 在错误
     *
     * @param session 会话
     * @param error   错误
     */
    @OnError
    public void one rror(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 发送消息
     *
     * @param message 消息
     */
    public void sendMessage(String message) {
        try {
            if (this.session != null) {
                this.session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送信息
     * 发送指定消息给某个用户
     *
     * @param userName 用户名
     * @param msgStr   消息信息
     */
    public static void sendInfo(String userName, String msgStr) {
        for (WebSocketServer item : webSocketSet) {
            if (item.loginName.equals(userName)) {
                item.sendMessage(msgStr);
            }
        }
    }
}

自己写个controller

进行调用测试服务端消息发送

    /***
     * userName 用户唯一标识 看你业务来 用户名称  用户id 都可以
     */
    @GetMapping("/sendMessage")
    public String sendMessage(String userName) {
 	// 发送消息提示到前端
 	WebSocketServer.sendInfo("这里是服务端发送的消息", userName);
        return "yes";
    }



前端搭建

一、index.vue

<!--============================================================================
  = - Yang Buyi  Copyright (c) 2021 https://yangbuyi.top.
  ===========================================================================-->

<template>
  <div class="webSocket">
    <button id="send" class="btn btn-default" @click="sendMsg('发送杨不易https://yangbuyi.top')">Send</button>
    <div v-for="item in msgData" :key="item">
      {{ item }}
    </div>
  </div>
</template>
<script>

export default {
  name: 'WebSocket',
  data() {
    return {
      // 消息
      msgData: [],
      websocket: null
    }
  },
  mounted() {
    this.connection()
    // this.initWebSocket()
  },
  destroyed() {
    if (this.websocket != null) this.websocket.close() // 离开路由之后断开websocket连接
  },
  methods: {
    initWebSocket() {
      this.connection()
      // const that = this
      // // 断开重连机制,尝试发送消息,捕获异常发生时重连
      // this.timer = setInterval(() => {
      //   try {
      //     that.websocket.send('hello')
      //   } catch (err) {
      //     console.log('断线了: ' + err)
      //     that.connection()
      //   }
      // }, 5000)
    },

    /**
     * 连接后台ws
     */
    connection() {
      const socketUrl = 'ws://localhost:你服务的端口/service_websocket/wspoint/' + '唯一名称'
      if (typeof (WebSocket) === 'undefined') {
        console.log('您的浏览器不支持WebSocket')
        this.$message.error('您的浏览器不支持WebSocket,无法使用推送功能!')
      } else {
        this.websocket = new WebSocket(socketUrl)
        console.log(this.websocket)
        this.websocket.onopen = this.websocketOnopen // 连接成功
        this.websocket.onmessage = this.websocketOnmessage // 广播成功
        this.websocket.onerror = this.websocketOnerror // 连接断开,失败
        this.websocket.onclose = this.websocketClose // 连接关闭
      }
    },
    websocketOnopen() {
      this.sendMsg('连接成功第一次https://yangbuyi.top')
      console.log('连接成功')
    },
    websocketOnerror() {
      console.log('连接失败')
    },
    websocketClose() {
      console.log('断开连接')
    },
    websocketOnmessage(data) {
       // 接收 服务端来的数据
      this.msgData.push(data)
    },
    sendMsg(val) {
      this.websocket.send(val)
    }
  }
}
</script>

测试调用创建的controller 向前端发送消息

标签:websocket,String,param,session,玩转,import,Websocket,public
From: https://www.cnblogs.com/Yangbuyi/p/17414670.html

相关文章

  • 从零玩转SpringSecurity+JWT整合前后端分离-从零玩转springsecurityjwt整合前后端分离
    title:从零玩转SpringSecurity+JWT整合前后端分离date:2021-05-0614:56:57.699updated:2021-12-2617:43:19.478url:https://www.yby6.com/archives/从零玩转springsecurityjwt整合前后端分离categories:-Java分类tags:-SpringSecurity-Jwt2021年4月9日·预......
  • 从零玩转Java和word模板-从零玩转java和word模板
    title:从零玩转Java和word模板date:2021-12-2218:38:14.086updated:2021-12-2218:38:14.086url:https://www.yby6.com/archives/从零玩转java和word模板categories:tags:前言公司需要使用生成word模板将Java信息输入到word指定位置......
  • 从零玩转Nginx
    01【熟悉】实际开发中的问题?现在我们一个项目跑在一个tomcat里面当一个tomcat无法支持高的并发量时。可以使用多个tomcat那么这多个tomcat如何云分配请求|-nginx02【熟悉】服务器概述1,目前常见的web服务器1,Apache(http://httpd.apache.org)它是世界上用的最多的web服务器,......
  • 【实践篇】教你玩转JWT认证---从一个优惠券聊起
    引言最近面试过程中,无意中跟候选人聊到了JWT相关的东西,也就联想到我自己关于JWT落地过的那些项目。关于JWT,可以说是分布式系统下的一个利器,我在我的很多项目实践中,认证系统的第一选择都是JWT。它的优势会让你欲罢不能,就像你领优惠券一样。大家回忆一下一个场景,如果你和你的女朋......
  • Websocket
    websocket是什么websocket与http一样都是OSI模型中应用层的协议,都是基于TCP协议来传输数据的,我们把这些更高级的协议理解成对TCP的封装。socket与websocket的关系socket与websocket的关系:就是毫无关系。socket并不是一种协议,而是一个抽象层,将物理层、数据链路层、网络层与传输......
  • 玩转MYSQL数据库之--视图详解
    前言从今天开始本系列文章就带各位小伙伴学习数据库技术。数据库技术是Java开发中必不可少的一部分知识内容。也是非常重要的技术。本系列教程由浅入深, 全面讲解数据库体系。 非常适合零基础的小伙伴来学习。全文大约【1297】字,不说废话,只讲可以让你学到技术、明白原理的纯......
  • .NET + SignalR 的反向代理 websocket/http 数据隧道
    开源项目TuToDataTunnel:https://github.com/viordash/TuToDataTunnel,这个项目可以满足以下几个需求:使用一个公网IP地址和一个tcp端口,默认端口为80http。Websocket或http隧道传输、性能或可访问性。理想情况下,将自动选择最佳可用交换协议。同时通过隧道传输多个TCP和u......
  • .Net Core 实现WebSocket Server 的另外三种方式
    回顾之前已经写过关于《WebSocket原生socket实现》和《.NetCoreWebSocket服务端与客户端完整示例》以及《基于.NetTcpListener实现WebSocketServer通讯》。其中除了《.NetCoreWebSocket服务端与客户端完整示例》外,都是基于自己对Websocket协议的实现,这种实现在生产环境......
  • 一图看懂CodeArts Deploy 5大特性,带你玩转部署服务
    华为云持续部署服务CodeArtsDeploy,通过模块化自由编排部署流程,实现软件的自动化部署,基于其易入门、功能全、集成度高、自动化、可靠的部署能力,能够帮您快速实现业务上云,全面提升软件的交付效率,显著提升交付质量! ......
  • 用QWebsocket时关于信号槽的一个坑
    https://blog.csdn.net/zerolity/article/details/94746977 坑描述:connect(&m_webSocket,&QWebSocket::textMessageReceived,this,&BWebsocket::onTextMessageReceived);1和主机通过websocket通信。接收主机发的指令有时导致重复接收。信号发送者和接受者同一线程。onTe......