zoukankan      html  css  js  c++  java
  • 如何使用WEBSOCKET实现前后端通信

    websocket通信是很好玩的,也很有用的的通信方式,使用方式如下:

    第一步由于springboot很好地集成了websocket,所以先在在pom.xml文件中引入依赖

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

    第二步在前端界面使用websocket,也就是HTML文件中编写

    复制代码
    <script>
        var websocket = null;
        if('WebSocket' in window) {
            websocket = new WebSocket('ws://yesell.natapp1.cc/sell/webSocket');
        }else {
            alert('该浏览器不支持websocket!');
        }
    
        websocket.onopen = function (event) {
            console.log('建立连接');
        }
    
        websocket.onclose = function (event) {
            console.log('连接关闭');
        }
    
        websocket.onmessage = function (event) {
            console.log('收到消息:' + event.data)
            //所要执行的操作
        }
    
        websocket.onerror = function () {
            alert('websocket通信发生错误!');
        }
    
        window.onbeforeunload = function () {
            websocket.close();
        }
    
    </script>
    复制代码

    第三步,一般我们是在controller层实现交互的,然而websocket的交互是在service层,

    其中:

    @ServerEndpoint("/webSocket")是定义了交互的地址
    @Slf4j是日志,有兴趣了解,请看这篇文章https://www.cnblogs.com/yemengshen/p/11478293.html
    @OnOpen、@OnClose、@OnMessage这三个方法与前端的三个同名方法相互交互,在需要使用的位置调用方法如下,
    到这里基本写完了。
    复制代码
    @Component
    @ServerEndpoint("/webSocket")
    @Slf4j
    public class WebSocket {
        private Session session;
        private static CopyOnWriteArraySet<WebSocket> webSocketSet=new CopyOnWriteArraySet<>();
        @OnOpen
        public void onOpen(Session session){
            this.session=session;
            webSocketSet.add(this);
            log.info("【websocket消息】有新的连接,总数:{}",webSocketSet.size());
        }
        @OnClose
        public void onClose(){
            webSocketSet.remove(this);
            log.info("【websocket消息】连接断开,总数:{}",webSocketSet.size());
        }
        @OnMessage
        public void onMessage(String message){
            log.info("【websocket消息】收到客户端发来的消息:{}",message);
        }
        public void sendMessage(String message){
            for(WebSocket webSocket:webSocketSet){
                log.info("【websocket消息】广播消息:{}",message);
                try {
                    webSocket.session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    复制代码

     使用方式:

    @Autowired
    private WebSocket webSocket;
    webSocket.sendMessage("传递的参数");
  • 相关阅读:
    Error:java: Annotation processing is not supported for module cycles. Please ensure that all modules from cycle [web_dao,web_service] are excluded from annotation processing
    手把手教你springboot中导出数据到excel中
    MySql多表关联Update笔记
    Spring Security踩坑记录(静态资源放行异常)
    Can't find bundle for base name
    简单好用的对象映射器——Mapster
    YARP简介 —— IHttpProxy
    使用Let's Encrypt创建SSL证书
    使用Mono.Cecil动态添加资源文件
    给RapiDoc添加多接口支持
  • 原文地址:https://www.cnblogs.com/xianz666/p/14416765.html
Copyright © 2011-2022 走看看