• SpingMvc +WebSocket实现简单的在线聊天


    概述

    WebSocket 是什么?

    WebSocket 是一种网络通信协议。RFC6455 定义了它的通信标准。

    WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。

    为什么需要 WebSocket ?

    了解计算机网络协议的人,应该都知道:HTTP 协议是一种无状态的、无连接的、单向的应用层协议。它采用了请求/响应模型。通信请求只能由客户端发起,服务端对请求做出应答处理。

    这种通信模型有一个弊端:HTTP 协议无法实现服务器主动向客户端发起消息。

    这种单向请求的特点,注定了如果服务器有连续的状态变化,客户端要获知就非常麻烦。大多数 Web 应用程序将通过频繁的异步JavaScript和XML(AJAX)请求实现长轮询。轮询的效率低,非常浪费资源(因为必须不停连接,或者 HTTP 连接始终打开)。

    因此,工程师们一直在思考,有没有更好的方法。WebSocket 就是这样发明的。WebSocket 连接允许客户端和服务器之间进行全双工通信,以便任一方都可以通过建立的连接将数据推送到另一端。WebSocket 只需要建立一次连接,就可以一直保持连接状态。这相比于轮询方式的不停建立连接显然效率要大大提高。

    WebSocket 如何工作?

    Web浏览器和服务器都必须实现 WebSockets 协议来建立和维护连接。由于 WebSockets 连接长期存在,与典型的HTTP连接不同,对服务器有重要的影响。

    基于多线程或多进程的服务器无法适用于 WebSockets,因为它旨在打开连接,尽可能快地处理请求,然后关闭连接。任何实际的 WebSockets 服务器端实现都需要一个异步服务器。

    现在我们来用代码实现一下简单的网页在线聊天

    1)项目基本结构

    2)、主要配置类(websocket有多种配置方法,这里主要讲在配置文件中配置)

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:websocket="http://www.springframework.org/schema/websocket"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:component-scan base-package="edu.nf.webscorks.controller"/>
    
        <mvc:annotation-driven/>
    
        <mvc:default-servlet-handler/>
    
        <!-- 配置WebSocket的handler -->
        <bean id="serverEndpoint" class="edu.nf.webscorks.webscoket.ServerEndpointHandler"/>
    
        <!-- 配置websocket -->
        <websocket:handlers>
            <!-- path为websocket连接的url,handler引用我们自定义的ServerEndpoint -->
            <websocket:mapping path="/websocket" handler="serverEndpoint"/>
            <!-- 配置HttpSession握手拦截器-->
            <!-- 说明:这个握手拦截器会将HttpSession中的数据拷贝到
                      WebSocketSession的属性中,因此在WebSocket中
                      也能访问会话作用域的信息-->
            <websocket:handshake-interceptors>
                <bean class="org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor"/>
            </websocket:handshake-interceptors>
        </websocket:handlers>
    </beans>

    3)、用户登录验证(controller)

    package edu.nf.webscorks.controller;
    
    /**
     * @author: lance
     * @date: 18-12-6
     */
    
    import edu.nf.webscorks.controller.vo.ResponseVO;
    import edu.nf.webscorks.entity.Users;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.servlet.http.HttpSession;
    
    @RestController
    public class UserController {
    
        /**
         * 验证用户账户登录
         * @param users
         * @param session
         * @return
         */
        @PostMapping("/userLogin")
        public ResponseVO login(Users users, HttpSession session){
            session.setAttribute("user",users);
            ResponseVO vo = new ResponseVO();
            vo.setCode(200);
            vo.setData("index.html");
            return vo;
        }
        
    }

    4)、实现TextWebSocketHandler类

    package edu.nf.webscorks.webscoket;
    
    import edu.nf.webscorks.entity.Users;
    import org.springframework.web.socket.CloseStatus;
    import org.springframework.web.socket.TextMessage;
    import org.springframework.web.socket.WebSocketSession;
    import org.springframework.web.socket.handler.TextWebSocketHandler;
    
    import java.util.Map;
    import java.util.concurrent.ConcurrentHashMap;
    
    /**
     * @author: lance
     * @date: 18-12-6
     */
    
    public class ServerEndpointHandler extends TextWebSocketHandler {
    
    
        /**
         * 维护一个用户列表(key存放用户名,value存放一个用户的WebSocketSession)
         */
        private static Map<String,WebSocketSession> users = new ConcurrentHashMap<>();
    
    
        /**
         * 客户端建立连接之后执行此方法(onOpen)
         * @param session 每当客户端连接之后,容器会其创建一个Session对象,
         *                这个对象在spring中就是WebSocketSession
         * @throws Exception
         */
        @Override
        public void afterConnectionEstablished(WebSocketSession session) throws Exception {
            System.out.println("客户端建立了连接...");
            //获取用户名,getAttributes方法得到的是一个Map
            //这个map里面存放了握手拦截器将HttpSession作用域拷贝过去的数据
            Users user = (Users)session.getAttributes().get("user");
            //将用户的session保存到用户列表中
            users.put(user.getUserName(),session);
        }
    
        @Override
        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
            System.out.println("接收客户端消息..." + message.getPayload());
            //获取用户名
            Users sendUser = (Users) session.getAttributes().get("user");
            //群发消息
            for(String userName:users.keySet()){
               //重新构建一个TextMessage
                TextMessage newMessage = new TextMessage(sendUser.getUserName() + " : " + message.getPayload());
                //发送所有人
                users.get(userName).sendMessage(newMessage);
            }
        }
    
    
        /**
         * 客户端关闭或断开连接时执行此方法(onClose)
         * @param session
         * @param status
         * @throws Exception
         */
        @Override
        public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
            System.out.println("客户端断开连接...");
            session.close();
        }
    }

    5)、登录和聊天页面

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>用户登录</title>
        <script src="js/jquery-3.3.1.min.js"></script>
    </head>
    <body>
     <form id="f1">
         Username:<input type="text" name="userName"/><br>
         Password:<input type="password" name="password"/><br>
         <input type="button" id="btn" value="login"/>
     </form>
    <script>
        $(function () {
            $('#btn').on('click',function () {
                var params = $('#f1').serialize();
                $.ajax({
                    url: 'userLogin',
                    type: 'post',
                    data: params,
                    success: function (result) {
                        if(result.code == 200){
                            location.href = result.data;
                        }else{
                            alert(result.message);
                        }
                    }
                });
            });
        })
    </script>
    </body>
    </html>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>聊天</title>
        <script src="js/jquery-3.3.1.min.js"></script>
    </head>
    <body>
      <div id="content"></div>
      <input type="text" id="msg" name="msg"/>
      <input type="button" value="send"/>
    <script>
        $(function () {
           var ws = new WebSocket('ws://localhost:8080/websocket');
           ws.onmessage = function (event) {
               $('#content').append(event.data + '<br>');
           }
           $(':button').on('click',function () {
               var msg = $('#msg').val();
               ws.send(msg);
           });
    
        })
    </script>
    </body>
    </html>

    效果展示

       websocket原理参照:http://www.cnblogs.com/slowcity/p/9293498.html

  • 相关阅读:
    谈谈Nullable<T>的类型转换问题
    MiniProfiler使用方法
    捕获变量
    web服务相关的问题或技巧
    对接mysql数据库遇见的一些问题
    委托
    导出到Excel
    斐波那契数列的运算时间
    .net framework摘抄与理解
    sql 语句
  • 原文地址:https://www.cnblogs.com/gepuginy/p/10110687.html
Copyright © 2020-2023  润新知