• 如何使用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("传递的参数");
  • 相关阅读:
    Unique constraint on single String column with GreenDao2
    Unique constraint on single String column with GreenDao
    将String转换成InputStream
    TypeError: unsupported operand type(s) for +: 'float' and 'str'
    Could not find private key file: AuthKey_NCD8233CS5.p8
    【Winows10】添加桌面小工具(在桌面显示时钟,日历)
    【Windows10】禁用开机启动项
    SQL如何查询出某一列中不同值出现的次数?
    使用 管理项目依赖
    Warning: Python 3.6 was not found on your system…
  • 原文地址:https://www.cnblogs.com/xianz666/p/14416765.html
Copyright © 2020-2023  润新知