spring boot websocket 客户端_SpringBoot集成websocket

原创 GoslingWu 架构师与哈苏

5a6cc0ef-a49c-43af-957c-3d5f9395559e

第一种:SpringBoot官网提供了一种websocket的集成方式

第二种:javax.websocket中提供了元注解的方式

下面讲解简单的第二种

添加依赖

org.springframework.boot                       spring-boot-starter-web                               org.springframework.boot            spring-boot-starter-tomcat                                  providedorg.springframework.boot            spring-boot-starter-websocket        

配置类

WebSocketConfig.java

package com.meeno.trainsys.websocket.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.socket.server.standard.ServerEndpointExporter;/** * @description: WebSocketConfig类 * @author: Wzq * @create: 2020-04-15 11:22 *///当我们使用外部Tomcat时,项目的管理权将会由Spring交接至Tomcat。// 而Tomcat7及后续版本是对websocket直接支持的,且我们所使用的jar包也是tomcat提供的。// 但是我们在WebSocketConfig中将ServerEndpointExporter指定给Spring管理。// 而部署后ServerEndpoint是需要Tomcat直接管理才能生效的。// 所以此时即就是此包的管理权交接失败,那肯定不能成功了。// 最后我们需要将WebSocketConfig中的bean配置注释掉@Configurationpublic class WebSocketConfig  {// 本地开发打开注释,打包成war注释掉再打包//    @Bean//    public ServerEndpointExporter serverEndpointExporter() {//        return new ServerEndpointExporter();//    }}

MeetingWebSocket.java

package com.meeno.trainsys.websocket.controller;import com.alibaba.fastjson.JSONObject;import com.alibaba.fastjson.serializer.SerializerFeature;import com.google.common.collect.Lists;import com.google.common.collect.Maps;import com.meeno.framework.constants.Constants;import com.meeno.framework.util.JsonUtils;import com.meeno.trainsys.user.service.UserMessageService;import com.meeno.trainsys.user.view.MeetingEmployeeChatListView;import com.meeno.trainsys.user.view.UserMessageListView;import com.meeno.trainsys.websocket.constants.SocketConstants;import com.meeno.trainsys.websocket.model.MeetingSocketModel;import com.meeno.trainsys.websocket.view.MeetingSocketView;import lombok.extern.java.Log;import lombok.extern.log4j.Log4j2;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;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.List;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;/** * @description: * @author: Wzq * @create: 2020-04-15 11:30 */@Component@ServerEndpoint("/websocket/{meetingId}/{empId}")@Logpublic class MeetingWebSocket {    private static UserMessageService userMessageService;    @Autowired    public void setUserMessageService(UserMessageService userMessageService){        MeetingWebSocket.userMessageService = userMessageService;    }    // concurrent包的线程安全Map,用来存放每个客户端对应的MyWebSocket对象。Long为会议室id    private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap();    //会议id    private Long meetingId;    //当前用户id    private Long userId;    // 当前聊天对象Session    private Session session;    // 未读数量    private Integer notReadNum;    /**     * 连接建立成功调用的方法*/    @OnOpen    public void onOpen(Session session, @PathParam("meetingId") Long meetingId,@PathParam("empId") Long empId) {        log.info("onOpen->meetingId:" + meetingId);        //创建一个会议webSocket        this.session = session;        this.meetingId = meetingId;        this.userId = empId;        webSocketMap.put(meetingId + "-" + userId,this);    }    /**     * 连接关闭调用的方法     */    @OnClose    public void onClose() {        log.info("onClose!");        //那个关闭了连接清空map        if(this.meetingId != null && this.userId != null){            String keyStr = this.meetingId + "-" + this.userId;            webSocketMap.remove(keyStr);        }    }    /**     * 收到客户端消息后调用的方法     * @param message     */    @OnMessage    public void onMessage(String message, Session session, @PathParam("meetingId") Long meetingId,@PathParam("empId") Long empId){        log.info("onMessage!" + message);        //发送消息给指定的人                this.sendMessageByUserId(1,model.getMeetingId(),model.getTargetEmpId());    }    /**     * 发生错误时调用     */    @OnError    public void onError(Session session, Throwable error){        log.info("webSocket发生错误!");        error.printStackTrace();    }    /**     * 根据会议id和用户id获取Socket     * @param meetingId     * @param userId     */    public static MeetingWebSocket getSocketByMeetingAndUserId(Long meetingId,Long userId){        for (String keyStr : webSocketMap.keySet()) {            String[] splitStr = keyStr.split("-");            String keyMeetingIdStr = splitStr[0];            if(meetingId.toString().equals(keyMeetingIdStr)){                if(webSocketMap.get(keyStr).userId.equals(userId)){                    MeetingWebSocket meetingWebSocket = webSocketMap.get(keyStr);                    return meetingWebSocket;                }            }        }        return null;    }    /**     * 根据会议和用户id发送消息     * @param msg     * @param meetingId     * @param userId     */    private void sendMessageByUserId(String msg,Long meetingId,Long userId){        for (String keyStr : webSocketMap.keySet()) {            String[] splitStr = keyStr.split("-");            String keyMeetingIdStr = splitStr[0];            if(meetingId.toString().equals(keyMeetingIdStr)){                if(webSocketMap.get(keyStr).userId.equals(userId)){                    MeetingWebSocket meetingWebSocket = webSocketMap.get(keyStr);                    meetingWebSocket.sendMessage(msg);                }            }        }    }    /**     * 发送消息     * @param msg     */    private void sendMessage(String msg){        try {            this.session.getBasicRemote().sendText(msg);        } catch (IOException e) {            e.printStackTrace();        }    }}

测试连接

8518efa7c2a44fef9af6f78d7e27d787

更多相关内容,Java&python,软件开发等学习资料,电子书及视频还有高级讲师公开课免费资源

需要的可以私聊小编发送【学习】二字

294a557702b0414b8fe9adfae3dbdbf5
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值