Java 使用websocket实现即时通讯(单聊)

1 websocket配置类

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

2 服务类

@Component
@ServerEndpoint(value = "/websocket/{userInfoId}")//这是链接地址:
public class WebSocketServer {
    //以用户的id为key,WebSocketServer为对象保存起来     *
    public static Map<String, WebSocketServer> clients = new ConcurrentHashMap<String, WebSocketServer>();
    //websocket不支持注入=============开始
    private static XXXService xxxService;
    
    @Autowired
    public void setTeamUserService(XXXService xxxService) {
        WebSocketServer.xxxService= xxxService;
    }

    //websocket不支持注入=============结束

    // 会话
    private Session session;
    // 用户id
    private String userInfoId;

    // 建立连接
    @OnOpen
    public void onOpen(@PathParam("userInfoId") String userInfoId, Session session) {
 
        //当前用户的信息 ========
        this.session = session;
        this.userInfoId = userInfoId;
        //当前用户的信息 ========
        //先判断当前用户是否在session中
        if (Objects.isNull(clients.get(userInfoId))) {
            clients.put(userInfoId, this);
        }
        //messageType 1代表刚刚上线返回当前用户所在群组  4代表普通消息
        //登录成功,返回当前用户所在的群组,并给所在群组的人发上线消息
        Map<String, Object> message = new HashMap<>();
        message.put("userInfoId", userInfoId);
        message.put("messageType", 1);
        
        try {
            sendMessageTo(JSONUtil.toJsonStr(message), userInfoId);
              //这是给所有人发一个当前用户上线得消息
            if (CollUtil.isNotEmpty(friends) && CollUtil.isNotEmpty(clients)) {
                for (int i = 0; i < friends.size(); i++) {
                    for (String str : clients.keySet()) {
                        if (str.equals(friends.get(i)) && !userInfoId.equals(str)) {
                            Map<String, Object> upMessage = new HashMap<>();
                            upMessage.put("userInfoId", userInfoId);
                            //messageType 2代表刚刚上线
                            upMessage.put("messageType", 2);
                            sendMessageTo(JSONUtil.toJsonStr(upMessage), str);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    //连接错误
    @OnError
    public void onError(Session session, Throwable error) {
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose(@PathParam("userInfoId") String userInfoId) {
        clients.remove(userInfoId);
        SysUserInfo userInfo = userInfoService.getOne(Wrappers.<SysUserInfo>query().lambda()
                .eq(SysUserInfo::getUserInfoId, userInfoId));
        userInfo.setUserInfoIsOnline(0);
        userInfoService.updateById(userInfo);
        //给所有人发一个下线消息
        if (CollUtil.isNotEmpty(clients)) {
            for (String str : clients.keySet()) {
                if (!userInfoId.equals(str)) {
                    Map<String, Object> upMessage = new HashMap<>();
                    upMessage.put("userInfoId", userInfoId);
                    //messageType 3代表下线
                    upMessage.put("messageType", 3);
                    try {
                        sendMessageTo(JSONUtil.toJsonStr(upMessage), str);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }


    /**
     * 收到客户端的消息 * @param message 消息* @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            //JSONUtil这里是用得hutool工具包
            HashMap hashMap = JSONUtil.toBean(message, HashMap.class);
            String textMessage = (String) hashMap.get("message");
            String userInfoId = (String) hashMap.get("userInfoId");
            //接收人的id
            String touserId = (String) hashMap.get("touserId");
            String messType = (String) hashMap.get("messType");
            //聊天记录的id
            String recordsId = (String) hashMap.get("recordsId");
            if (messType.equals("4")) {
                SysUserChatRecords chatRecords = chatRecordsService.getById(recordsId);
                chatRecords.setUserChatRecordsIsRead(1);
                chatRecordsService.updateById(chatRecords);
            } else {
                Map<String, Object> map = new HashMap<>();
                map.put("textMessage", textMessage);
                map.put("userInfoId", userInfoId);
                map.put("touserId", touserId);
                sendMessageTo(JSONUtil.toJsonStr(map), touserId);
                SysUserChatRecords userChatRecords = new SysUserChatRecords();
                userChatRecords.setUserChatRecordsContent(textMessage);
                userChatRecords.setUserChatRecordsTime(new Date());
                userChatRecords.setUserChatRecordsAcceptUserId(touserId);
                userChatRecords.setUserChatRecordsToUserId(userInfoId);
                userChatRecords.setUserChatRecordsType(messType);
                if (Objects.nonNull(clients.get(touserId))) {
                    userChatRecords.setUserChatRecordsIsRead(1);
                } else {
                    userChatRecords.setUserChatRecordsIsRead(0);
                }
                userChatRecords.setUserChatRecordsThisUserId(userInfoId);
                chatRecordsService.save(userChatRecords);
                SysUserChatRecords userChatRecordsF = new SysUserChatRecords();
                userChatRecordsF.setUserChatRecordsContent(textMessage);
                userChatRecordsF.setUserChatRecordsTime(new Date());
                userChatRecordsF.setUserChatRecordsAcceptUserId(touserId);
                userChatRecordsF.setUserChatRecordsToUserId(userInfoId);
                userChatRecordsF.setUserChatRecordsType(messType);
                if (Objects.nonNull(clients.get(touserId))) {
                    userChatRecordsF.setUserChatRecordsIsRead(1);
                } else {
                    userChatRecordsF.setUserChatRecordsIsRead(0);
                }
                userChatRecordsF.setUserChatRecordsThisUserId(touserId);
                chatRecordsService.save(userChatRecordsF);
            }
        } catch (Exception e) {
        }
    }


    public void sendMessageTo(String message, String touserId) throws IOException {
        for (WebSocketServer item : clients.values()) {
            if (item.userInfoId.equals(touserId)) {
                item.session.getAsyncRemote().sendText(message);
                break;
            }
        }
    }
}

3 存消息得实体类 看着建一个就行了

4 html页面

<!DOCTYPE html><html>
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>    <title>websocket</title>
  <script src="/js/sockjs.min.js"></script>
  <script src="/js/stomp.min.js"></script>
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>

<div style="margin: auto;text-align: center">
  <select id="onLineUser">
    <option>--所有--</option>
  </select>
  <input id="text" type="text" />
  <button id="send" >发送消息</button>
</div>
<br>
<div style="margin-right: 10px;text-align: right">
  <button id="closeWebSocket" onclick="closeWebSocket()">关闭连接</button>
</div><hr/>

<div id="message" style="text-align: center;">
</div><input  type="text"  id="userInfoId" style="display: none" />

</body>

<script type="text/javascript">
  function thiswebsocket(){
    var webSocket;
    var usersN=$("#userInfoId").val();
    if ("WebSocket" in window)
      //查看websocket是否存在
       {
//连接到websocket
      webSocket = new WebSocket("ws://IP地址:端口/websocket/"+usersN);
//接收后台服务端的消息
    webSocket.onmessage = function (evt){
//evt:是后台传出来的所有信息
//evt.data是后台传出来的类型,还有在线用户
      var received_msg = evt.data;
      var obj = JSON.parse(received_msg);
      console.log(obj);
    };
//连接关闭的回调事件
    webSocket.onclose = function()
    {
      console.log("连接已关闭...");
    };

      webSocket.onerror= function () {
        console.log("cuowu")
      }
  }      else{
// 浏览器不支持 WebSocket
    alert("您的浏览器不支持 WebSocket!");
  }


  //关闭连接
  $("#closeWebSocket").click(function () {
    webSocket.close();
  });


  //发送的事件
  $("#send").click(function () {

    var message
//message:所有信息:发送人,接收人,信息
    var message = {
      "message":"在不在?",
      "userInfoId":usersN,
      "touserId":"cdc41e112a624d2c872af85b44214630",
      "messType":"1"
    };
//将消息传送到后端服务器
    webSocket.send(JSON.stringify(message));
    $("#text").val("");
  });
  }



  $(function() {
    $("#userInfoId").val(getQueryVariable("userInfoId"));
    thiswebsocket();
  });


  //获取路径中的名字
  function getQueryVariable(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var index = window.location.href.indexOf("?");
    var query = window.location.href.substr(1).substring(index);
    var r = query.match(reg);
    if ( r != null ){
      return decodeURI(r[2]);
    }else{
      return null;
    }
  }
</script>
</html>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值