webSocket聊天系统

引入依赖

<!-- 引入webSocket依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>2.5.2</version>
        </dependency>

webSocket配置类

package com.example.websocket.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
 
/**
 * wyl 2021/8/24
 */
@Configuration
public class WebSocketConfig
{
    @Bean
    public ServerEndpointExporter serverEndpointExporter()
    {
        return new ServerEndpointExporter();
    }
}

webSocket实时聊天类

package com.jiukuang.api.webSocket;


import com.alibaba.fastjson.JSONObject;
import com.jiukuang.api.result.util.ResultUtil;
import com.jiukuang.baseinterface.IUserBaseService;
import com.jiukuang.baseinterface.SocketFriendBaseService;
import com.jiukuang.baseinterface.SocketMessageBaseService;
import com.jiukuang.dao.myMapper.SocketFriendDao;
import com.jiukuang.dao.myMapper.SocketMessageDao;
import com.jiukuang.enums.ResultEnum;
import com.jiukuang.exceptions.YQSException;
import com.jiukuang.pojo.SocketFriend;
import com.jiukuang.pojo.SocketMessage;
import com.jiukuang.pojo.User;
import com.jiukuang.utils.SpringBeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
 
/**
 * websocket实现实时聊天
 */
@Slf4j
@Component
@ServerEndpoint(value = "/websocket/{userId}/{receiveUserId}")
public class MyWebSocket {


    public static MyWebSocket webSocketServer;
    @PostConstruct
    public void init(){
        webSocketServer = this;
    }
    /**
     * 在线人数
     */
    public static int onlineNumber = 0;
 
    /**
     * 所有的对象
     */
//    public static List<MyWebSocket> webSockets = new CopyOnWriteArrayList<MyWebSocket>();
    /**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap<String,MyWebSocket> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 会话
     */
    private Session session;

    /**发送userId*/
    private Integer userId;
    /**接收userId*/
    private Integer receiveUserId;
    /**双方用户基础信息*/
    private  SocketFriend socketFriend;
    private  SocketFriend socketFriend1;
    /**双方用户基础信息*/
    private  SocketMessage socketMessage;

 
    /**
     * 建立连接
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Integer userId, @PathParam("receiveUserId") Integer receiveUserId) {
        this.session = session;
        this.userId=userId;
        this.receiveUserId=receiveUserId;
        this.socketMessage=new SocketMessage();
        this.socketFriend=new SocketFriend();
        this.socketFriend1=new SocketFriend();
        /**查询双方用户信息*/
        IUserBaseService iUserBaseService = SpringBeanUtil.getBean(IUserBaseService.class);
        User user = iUserBaseService.selectById(userId);
        User receiveUser = iUserBaseService.selectById(receiveUserId);
        if (ObjectUtils.isEmpty(user)){
            Throwable error = new Throwable("用户不存在");
            onError(session,error);
        }else {
            /**设置消息已读*/
            SocketMessageDao socketMessageDao = SpringBeanUtil.getBean(SocketMessageDao.class);
            socketMessageDao.update_UserIdAndReceiveUserId_read(userId,receiveUserId,1);

            //关系表
            this.socketFriend.setUserId(user.getUId());
            this.socketFriend.setUserNickName(user.getUName());
            this.socketFriend.setUserHead(user.getProfilePicture());
            this.socketFriend.setFriendUserId(receiveUser.getUId());
            this.socketFriend.setFriendNickName(receiveUser.getUName());
            this.socketFriend.setFriendHead(receiveUser.getProfilePicture());
            this.socketFriend1.setUserId(receiveUser.getUId());
            this.socketFriend1.setUserNickName(receiveUser.getUName());
            this.socketFriend1.setUserHead(receiveUser.getProfilePicture());
            this.socketFriend1.setFriendUserId(user.getUId());
            this.socketFriend1.setFriendNickName(user.getUName());
            this.socketFriend1.setFriendHead(user.getProfilePicture());

            //消息表
            this.socketMessage.setUserId(user.getUId());
            this.socketMessage.setUserNickName(user.getUName());
            this.socketMessage.setUserHead(user.getProfilePicture());
            this.socketMessage.setReceiveUserId(receiveUser.getUId());
            this.socketMessage.setReceiveNickName(receiveUser.getUName());
            this.socketMessage.setReceiveHead(receiveUser.getProfilePicture());
            /**须用该工具类获取Bean对象否则webSocket获取不到Bean对象不能对数据库进行操作*/
            SocketFriendBaseService socketFriendBaseService = SpringBeanUtil.getBean(SocketFriendBaseService.class);
            SocketFriendDao socketFriendDao = SpringBeanUtil.getBean(SocketFriendDao.class);
            /**数据库操作*/
            SocketFriend socketFriend = socketFriendDao.select_UserIdAndFriendUserId(this.socketFriend.getUserId(), this.socketFriend.getFriendUserId());
            SocketFriend socketFriend1 = socketFriendDao.select_UserIdAndFriendUserId(this.socketFriend.getFriendUserId(), this.socketFriend.getUserId());
            /**
             * 双方添加关系
             */
            if (ObjectUtils.isEmpty(socketFriend)){
                /**新增关系*/
                socketFriendBaseService.insertSelective(this.socketFriend);
            }else {
                //是否已删除
                if (socketFriend.getIsDelete()==1){
                    socketFriend.setIsDelete(0);
                }
                /**修改关系*/
                socketFriendBaseService.updateSelective(socketFriend);
            }
            if (ObjectUtils.isEmpty(socketFriend1)){
                /**新增关系*/
                socketFriendBaseService.insertSelective(this.socketFriend1);
            }else {
                //是否已删除
                if (socketFriend1.getIsDelete()==1){
                    socketFriend1.setIsDelete(0);
                }
                /**修改关系*/
                socketFriendBaseService.updateSelective(socketFriend1);
            }
            //判断该用户是否在线
            if(webSocketMap.containsKey(userId+""+receiveUserId)){
                webSocketMap.remove(userId+""+receiveUserId);
                webSocketMap.put(userId+""+receiveUserId,this);
            }else {
                webSocketMap.put(userId+""+receiveUserId,this);
                //在线人数+1
                addOnlineCount();
                log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());
                log.info("用户连接:"+JSONObject.toJSON(webSocketMap.keys()));

            }
            //发送消息
            sendMessage("连接成功");
        }
    }
 
    /**
     * 连接关闭
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(userId+""+receiveUserId)){
            webSocketMap.remove(userId+""+receiveUserId);
            //在线人数-1
            subOnlineCount();
        }
        log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
    }
 
    /**
     * 收到客户端的消息
     *
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户消息:"+userId+",报文:"+message);
        //可以群发消息
        //消息保存到数据库、redis
        if (!StringUtils.isEmpty(message)){
            try {
                SocketMessage socketMessage2 = this.socketMessage;
                socketMessage2.setMessage(message);
                socketMessage2.setSendDate(System.currentTimeMillis());
                /**须用该工具类获取Bean对象否则webSocket获取不到Bean对象不能对数据库进行操作*/
                SocketMessageBaseService socketMessageBaseService = SpringBeanUtil.getBean(SocketMessageBaseService.class);
                if (webSocketMap.get(receiveUserId+""+userId)!=null){
                    if (webSocketMap.containsKey(receiveUserId+""+userId)){
                        socketMessage2.setIsRead(1);
                        webSocketMap.get(receiveUserId+""+userId).sendMessage(message);
                    }else {
                        socketMessage2.setIsRead(0);
                        log.error("请求的receiveUserId+userId:"+receiveUserId+""+userId+"不在该服务器上");
                    }
                }else {
                    socketMessage2.setIsRead(0);
                }
                /**存入消息*/
                socketMessageBaseService.insertSelective(socketMessage2);
            }catch (Exception e){
                e.printStackTrace();
            }
            sendMessage(message);
        }
    }
 
    /**
     * 发送消息
     *
     * @param message 消息
     */
    public void sendMessage(String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
        error.printStackTrace();
    }


    public static synchronized int getOnlineCount() {
        return onlineNumber;
    }

    public static synchronized void addOnlineCount() {
        MyWebSocket.onlineNumber++;
    }

    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineNumber--;
    }


}

自己写的辣鸡页面,仅供测试参考:html页面一对一聊天

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>welcome</title>
</head>
<body>
<div>你好</div>
自己<input id="my" type="text"/><br>
接收消息人<input id="receive" type="text"/><br>
<button onclick="start()">点击建立连接</button><br>
<div style="width: 300px;height: 300px;border: 1px solid black;display: inline-block">
    <ul id="messageList">
    </ul>
</div>
<button onclick="getMessage1()">点击获取消息列表</button>
<div  style="width: 100px;height: 300px;border: 1px solid black;display: inline-block">
    <ul id="firstList">
    </ul>
</div>
<button onclick="getFirst()">点击获取好友列表</button>
<div><input id="sendMessage" style="height: 100px; width: 200px"/><button onclick="sendMessage()">点击发送</button></div>

</body>

<script>

    var webSocket;
    var my;
    var receive;
    var postValue;
    var getValue={};
    function start(){
        my = document.getElementById('my').value
        receive= document.getElementById('receive').value
        if (window.WebSocket) {
            webSocket = new WebSocket("ws://192.168.1.109:8080/websocket/"+my+"/"+receive);

            //连通之后的回调事件
            webSocket.onopen = function() {};

            //接收后台服务端的消息
            webSocket.onmessage = function (evt) {
                var message = evt.data;
                 var li = document.createElement("li")
                li.innerHTML = message
                document.getElementById('messageList').appendChild(li)
            };

            //连接关闭的回调事件
            webSocket.onerror = function(evt) {
                console.log(evt.currentTarget)
            };

            //连接关闭的回调事件
            webSocket.onclose = function() {
                // alert("连接已关闭...");
            };
        }
    }
    function getFirst(){
        my = document.getElementById('my').value
        if (my==""){
            alert("用户ID不能为空")
        }else {
            getAjax('http://192.168.1.109:8080/socket/get_userFriend?userId='+my)
            for (let i in getValue.data) {
                var li = document.createElement("li")
                li.innerHTML = getValue.data[i].friendNickName
                document.getElementById('firstList').appendChild(li)
            }
        }
    }
    function getMessage1(){
        my = document.getElementById('my').value
        receive= document.getElementById('receive').value
        if (my=="" || receive==""){
            alert("双方用户ID都不可为空")
        }else {
            getAjax('http://192.168.1.109:8080/socket/get_userMessage?userId='+my+'&receiveUserId='+receive)
            for (let i in getValue.data) {
                var li = document.createElement("li")
                li.innerHTML = getValue.data[i].message
                document.getElementById('messageList').appendChild(li)
            }
        }
    }



    function postAjax(stringData,path){
        var xhr = new XMLHttpRequest()
// open 方法的第一个参数的作用就是设置请求的 method
//         xhr.open('POST', './add.php')
        xhr.open('POST', path)
// 设置请求头中的 Content‐Type 为 application/x‐www‐form‐urlencoded
// 标识此次请求的请求体格式为 urlencoded 以便于服务端接收数据
        xhr.setRequestHeader('Content‐Type', 'application/x‐www‐form‐urlencoded')
// 需要提交到服务端的数据可以通过 send 方法的参数传递
// 格式:key1=value1&key2=value2
//         xhr.send('key1=value1&key2=value2')
        xhr.send(stringData)
        xhr.onreadystatechange = function () {
            if (this.readyState === 4) {
                postValue=this.responseText
                console.log(this.responseText)
            }
        }
    }


    function getAjax(path){
        var xhr = new XMLHttpRequest()
// GET 请求传递参数通常使用的是问号传参
// 这里可以在请求地址后面加上参数,从而传递数据到服务端
        xhr.open('GET', path)
// 一般在 GET 请求时无需设置响应体,可以传 null 或者干脆不传
        xhr.send(null)
        xhr.onreadystatechange = function () {
            if (this.readyState === 4) {
                // getValue=this.responseText
                getValue= eval('(' + this.responseText + ')');  // 把JSON字符串解析为javascript对象
                console.log(getValue)
            }
        }
// 一般情况下 URL 传递的都是参数性质的数据,而 POST 一般都是业务数据

    }


    //发送消息
    function sendMessage(){
        webSocket.send(document.getElementById('sendMessage').value)
    }

</script>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值