websocket在springboot项目中的简单使用

WebSocket 在springboot项目中的简单应用



首先是springboot项目的启动方式,根据不同的启动方式,导入WebSocket对的方式不同。

  1. springboot项目启动直接使用启动类方式

    首先在pom文件中导入依赖

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

    创建WebSocketServer类,建议放在controller层

    package ncu.graduation.hzl.controller;
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import org.springframework.stereotype.Component;
    
    import javax.websocket.OnClose;
    import javax.websocket.OnError;
    import javax.websocket.OnMessage;
    import javax.websocket.OnOpen;
    import javax.websocket.Session;
    import javax.websocket.server.PathParam;
    import javax.websocket.server.ServerEndpoint;
    import java.io.IOException;
    import java.util.concurrent.ConcurrentHashMap;
    
    @ServerEndpoint("/ws/{userId}")
    @Component
    public class WebSocketServer {
    
        /**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
        private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<String,WebSocketServer>();
        /**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
        private Session session;
    
        /**接收userId*/
        private String userId="";
    
        /**
         * 连接建立成功调用的方法*/
        @OnOpen
        public void onOpen(Session session, @PathParam("userId") String userId) {
            this.session = session;
            if(webSocketMap.containsKey(userId)){
                webSocketMap.remove(userId);
                webSocketMap.put(userId,this);
            }else{
                webSocketMap.put(userId,this);
            }
    
            System.out.println("当前连接用户:"+userId);
    
        }
    
        /**
         * 连接关闭调用的方法
         */
        @OnClose
        public void onClose() {
            if(webSocketMap.containsKey(userId)){
                webSocketMap.remove(userId);
            }
            System.out.println("用户 "+userId+" 退出:");
        }
    
        /**
         * 收到客户端消息后调用的方法
         *
         * @param message 客户端发送过来的消息*/
        @OnMessage
        public void onMessage(String message, Session session) {
            System.out.println("收到用户消息:"+userId+",报文:"+message);
            if(!"".equals(message)){
                try {
                    //解析发送的报文
                    JSONObject jsonObject = JSON.parseObject(message);
                    //追加发送人(防止串改)
                    jsonObject.put("fromUserId",this.userId);
                    String toUserId=jsonObject.getString("toUserId");
                    //传送给对应toUserId用户的websocket
                    if(!"".equals(toUserId) && webSocketMap.containsKey(toUserId)){
                        webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
                    }else{
                        webSocketMap.get(this.userId).sendMessage("请求的userId:"+toUserId+"不在该服务器上");
                        System.out.println("请求的userId:"+toUserId+"不在该服务器上");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    
        /**
         *
         * @param session
         * @param error
         */
        @OnError
        public void onError(Session session, Throwable error) {
            System.out.println("用户错误:"+this.userId+",原因:"+error.getMessage());
            error.printStackTrace();
        }
    
        /**
         * 实现服务器主动推送
         */
        public void sendMessage(String message) throws IOException {
            if(this.session != null) {
                this.session.getAsyncRemote().sendText(message);
            }
        }
    
        /**
         * 发送自定义消息
         * */
        public static void sendInfo(String message, String userId) throws IOException {
    
            System.out.println("发送消息到:"+userId+",报文:"+message);
            if(!"".equals(userId) && webSocketMap.containsKey(userId)){
                webSocketMap.get(userId).sendMessage(message);
            }else{
                System.out.println("用户"+userId+",不在线!");
            }
        }
    
        public static ConcurrentHashMap<String, WebSocketServer> getWebSocketMap() {
            return webSocketMap;
        }
    
        public static void setWebSocketMap(ConcurrentHashMap<String, WebSocketServer> webSocketMap) {
            WebSocketServer.webSocketMap = webSocketMap;
        }
    }
    

    项目启动类中添加如下配置

    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
    

    前端创建test.html文件

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>websocket通讯</title>
    </head>
    //注意换成自己的js文件位置
    <script src="../layui/js/jquery-3.3.1.js"></script>
    <script>
        var socket;
        //开启连接
        function openSocket() {
            if(typeof(WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            }else{
                if (!$("#fromUserId").val()){
                    alert("请输入用户名");
                    return;
                }
                console.log("您的浏览器支持WebSocket");
                //实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接
                //等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
                //var socketUrl="${request.contextPath}/im/"+$("#userId").val();
                var socketUrl="http://localhost:8080/ws/"+$("#fromUserId").val();
                socketUrl=socketUrl.replace("https","ws").replace("http","ws");
                console.log(socketUrl);
                if(socket!=null){
                    socket.close();
                    socket=null;
                }
                socket = new WebSocket(socketUrl);
                //打开事件
                socket.onopen = function() {
                    console.log("websocket已打开");
                    $("#allContent")
                        .append("<div>" + "收到消息:已建立连接,"+new Date() + "</div>");
                };
                //获得消息事件
                socket.onmessage = function(msg) {
                    $("#allContent")
                        .append("<div>" + "收到消息" +":"+msg.data + "</div>");
                    console.log(msg.data);
                };
                //关闭事件
                socket.onclose = function() {
                    $("#allContent")
                        .append("<div>" + "收到消息:websocket已关闭,"+new Date() + "</div>");
                    console.log("websocket已关闭");
                };
                //发生了错误事件
                socket.onerror = function() {
                    $("#allContent")
                        .append("<div>" + "收到消息:websocket连接发生了错误,"+new Date() + "</div>");
                    console.log("websocket发生了错误");
                }
            }
        }
        // 关闭连接
        function closeSocket() {
            if (socket){
                socket.disconnect();
            }
        }
        // 发送消息
        function sendMessage() {
            if(typeof(WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            }else {
                // 判断是否已建立连接
                if (socket){
                    socket.send('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
                }else {
                    alert("请先建立连接");
                }
    
            }
        }
    </script>
    <body>
    【请输入用户名】:<input id="fromUserId" name="fromUserId" type="text" value="admin"/>
    【目标用户名】:<input id="toUserId" name="toUserId" type="text" value="qxf"/>
    <button onclick="openSocket()"  style="color:red;">开启连接</button>
    <button onclick="closeSocket()"  style="color:red;">关闭连接</button>
    <button onclick="sendMessage()" style="color:blue;">发送消息</button>
    【内容】:<input id="contentText" name="contentText" type="text" value="hello websocket">
    <div id="allContent">
    
    </div>
    </body>
    
    </html>
    

    之后测试连接就可以了

  2. springboot项目使用外置tomcat方式启动

    此方式启动springboot项目的话,不用导入websocket的依赖,并且不用在启动类中添加配置,直接使用外部容器中的jar包,项目运行在外部的tomcat中,首先将websocket的jar包添加到tomcat下面的lib文件夹中
    图片1

​ 然后在idea中配置引用tomcat中jar包,在Setting中查找Application Servers,然后把需要的jar加进来。

图片2

​ 最后加入项目的依赖中

图片3

完成之后,前端测试页面内容不变,可以进行测试了

转载于1https://blog.csdn.net/qiuxinfa123/article/details/106441492

转载于2https://blog.csdn.net/weferxe/article/details/91047676

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值