Java后台使用Websocket教程

时间:2022-02-26 04:30:54

在开发一个项目的时候使用到了WebSocket协议

  1. 什么是WebSocket?  

      WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

   2.使用

      • 工具类 
         package com.mz.usps.common.component;
        
         import org.apache.log4j.Logger;
        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.concurrent.ConcurrentHashMap;
        import java.util.concurrent.ConcurrentMap; //该注解用来指定一个URI,客户端可以通过这个URI来连接到WebSocket。类似Servlet的注解mapping。无需在web.xml中配置。
        @ServerEndpoint("/webSocket/{id}")
        @Component("webSocket")
        public class WebSocket { private static Logger logger = Logger.getLogger(WebSocket.class);
        //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
        private static int onlineCount = 0;
        //与某个客户端的连接会话,需要通过它来给客户端发送数据
        private Session session;
        //concurrent包的线程安全Map,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
        private static ConcurrentMap<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();
        private static ConcurrentMap<String, WebSocket> webSocketMapAdmin = new ConcurrentHashMap<>(); public Session getSession() {
        return session;
        } public static WebSocket getWebSocket(String id) {
        return webSocketMap.get(id);
        } /**
        * 连接建立成功调用的方法
        *
        * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
        */
        @OnOpen
        public void onOpen(Session session, @PathParam("id") String id) {
        this.session = session;
        //String sessionId = session.getId();
        webSocketMap.put(id, this); //加入map中
        if (id.contains("admin")) {// 后台登陆用户,加入list
        webSocketMapAdmin.put(id, this);
        }
        addOnlineCount(); //在线数加1
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
        } /**
        * 连接关闭调用的方法
        */
        @OnClose
        public void onClose(@PathParam("id") String id) {
        webSocketMap.remove(id); //从map中删除
        webSocketMapAdmin.remove(id);
        subOnlineCount(); //在线数减1
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
        } /**
        * 收到客户端消息后调用的方法
        *
        * @param message 客户端发送过来的消息
        * @param session 可选的参数
        */
        @OnMessage
        public static void onMessage(String message, Session session) {
        //群发消息
        if (webSocketMapAdmin.size() > 0) {
        for (WebSocket item : webSocketMapAdmin.values()) {
        try {
        //System.out.println(item.session.getId());
        item.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
        logger.error("IO异常");
        continue;
        }
        }
        } } /**
        * 发生错误时调用
        *
        * @param session
        * @param error
        */
        @OnError
        public void onError(Session session, Throwable error) {
        //System.out.println("发生错误");
        logger.error("发生错误");
        } /**
        * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
        *
        * @param message
        * @throws IOException
        */
        public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
        } public static synchronized int getOnlineCount() {
        return onlineCount;
        } public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
        } public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
        } public static void main(String[] args) {
        /*WebSocket webSocket = new WebSocket();
        System.out.println(webSocket);
        webSocketMap.put("1", webSocket);
        webSocketMap.put("1", webSocket);
        System.out.println(webSocketMap.get("12"));*/
        onMessage("123465",null);
        }
        }
      • 微信登录成功时将用户信息发送给前端
      •  /**
        * 手机端微信登陆
        *
        * @return
        */
        @RequestMapping(value = "/wxLogin", method = RequestMethod.GET)
        @ResponseBody
        public R wxLogin(String userResult, String state, @RequestParam(required = false, value = "userId") String userId) throws Exception {
        //System.out.println(userResult+"\n"+state+"\n"+userId);
        WxUser wxUser = JSON.parseObject(userResult, WxUser.class);
        UserInfo userInfo = new UserInfo();
        userInfo.setUnionId(wxUser.getUnionid());
        userInfo.setOpenid(wxUser.getOpenid());
        userInfo.setSex((long) wxUser.getSex());
        userInfo.setHeadImgUrl(wxUser.getHeadimgurl());
        if (EmojiUtil.containsEmoji(wxUser.getNickName())) {
        logger.info(wxUser.getNickName());
        userInfo.setNickName(EmojiUtil.emojiConverterToAlias(wxUser.getNickName()));
        } else {
        userInfo.setNickName(wxUser.getNickName());
        }
        System.out.println(userInfo.getUnionId());
        UserInfo userInfo1;
        WebSocket webSocket = WebSocket.getWebSocket(state);
        Map<String, Object> m = new HashMap<>();
        //登录
        if (userId == null || "".equals(userId)) {
        if ((userInfo1 = userInfoService.selectWx(userInfo)) != null) {
        //判定账号是否被禁用
        if (userInfo1.getUserState() != 1) {
        R r = new R();
        r.put("code", 500);
        r.put("msg", "此账号因为特殊原因已被禁用,若想重新启用,请联系管理员");
        webSocket.sendMessage(JSON.toJSONString(r));
        return null;
        } userInfo.setUserId(userInfo1.getUserId());
        //System.out.println(userInfo1.getHeadImgUrl()+"你好呀");
        if (userInfo1.getHeadImgUrl() != null) {
        userInfo.setHeadImgUrl(null);
        }
        //System.out.println(userInfo.getHeadImgUrl()+"你好");
        userInfoService.updateByPrimaryKeySelective(userInfo);
        UserInfo userInfo2 = userInfoService.selectWx(userInfo);
        if (EmojiUtil.containsEmoji(userInfo2.getNickName())) {
        userInfo2.setNickName(EmojiUtil.emojiConverterUnicodeStr(userInfo2.getNickName()));
        }
        m.put("openId", userInfo2.getOpenid());
        m.put("userId", userInfo2.getUserId());
        m.put("createTime", new Date());
        String javaWebToken = WebTokenUtil.createJavaWebToken(m);
        userInfo2.setToken(javaWebToken);
        redisCache.setValue(javaWebToken, "1", 1, TimeUnit.DAYS);
        webSocket.sendMessage(JSON.toJSONString(userInfo2));//登录用户信息发送给web
        return R.ok("登录成功");
        } else {
        userInfo.setUserName(userInfo.getNickName());
        userInfoService.insertSelective(userInfo);
        UserInfo userInfo3 = userInfoService.selectWx(userInfo);
        if (EmojiUtil.containsEmoji(userInfo3.getNickName())) {
        userInfo3.setNickName(EmojiUtil.emojiConverterUnicodeStr(userInfo3.getNickName()));
        }
        //判定账号是否被禁用
        if (userInfo3.getUserState() != 1) {
        R r = new R();
        r.put("code", 500);
        r.put("msg", "此账号因为特殊原因已被禁用,若想启用,请联系管理员");
        webSocket.sendMessage(JSON.toJSONString(r));
        return null;
        } System.out.println(userInfo.getOpenid());
        m.put("openId", userInfo3.getOpenid());
        m.put("userId", userInfo3.getUserId());
        m.put("createTime", new Date());
        String javaWebToken = WebTokenUtil.createJavaWebToken(m);
        userInfo3.setToken(javaWebToken);
        redisCache.setValue(javaWebToken, "1", 1, TimeUnit.DAYS);
        webSocket.sendMessage(JSON.toJSONString(userInfo3));//登录用户信息发送给web
        return R.ok("登录成功");
        }
        } else {
        userInfo.setUserId(Long.valueOf(userId));
        //绑定微信前先判断数据库中是否有头像,如果有,不更改头像
        List<UserInfo> selectmemberlist = userInfoService.selectmemberlist(userInfo);
        if (selectmemberlist.get(0).getHeadImgUrl() != null) {
        userInfo.setHeadImgUrl(null);
        } UserInfo userInfo2 = userInfoService.selectWx(userInfo);
        if (userInfo2 != null) {
        R r = new R();
        r.put("code", 500);
        r.put("msg", "此微信已被注册,若确认是你本人微信,请联系管理员帮你更改");
        webSocket.sendMessage(JSON.toJSONString(r));
        return R.error("");
        }
        if (EmojiUtil.containsEmoji(wxUser.getNickName())) {
        userInfo.setNickName( EmojiUtil.emojiConverterToAlias(wxUser.getNickName()));
        }
        R r = userInfoService.updateByPrimaryKeySelective(userInfo);
        if (r.get("code").equals(200)) {
        R r1 = new R();
        r1.put("code", 200);
        r1.put("msg", "更改成功");
        webSocket.sendMessage(JSON.toJSONString(r1));
        } else {
        R r2 = new R();
        r2.put("code", 500);
        r2.put("msg", "更改失败");
        webSocket.sendMessage(JSON.toJSONString(r2));
        }
        return r;
        }
        } }