欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot练习--利用websocket实现QQ聊天室

程序员文章站 2022-03-09 23:13:57
...

本篇介绍websocket实现QQ聊天室的后端实现,前端的实现看链接说明

链接说明

1.使用了spring boot 框架,有关spring boot 入门请戳此链接使用Intellij IDEA开发第一个spring boot项目
2.安卓前端实现细节戳此链接安卓android+WebSocket实现简易QQ聊天室

界面演示

说明

有两个界面,第一个是登陆界面,我借用了我之前实现的登陆界面,并做了一些微调。需要输入ID和名字,测试的时候输入的ID不能重复,第二个是名字用于界面展示,登陆后跳转入第二个界面,就可以在聊天室里聊天了。

下面图模拟了一组场景,大青儿先进入聊天室,然后小明进入,互相发一段消息后,小明退出聊天室。

大青儿界面变化

spring boot练习--利用websocket实现QQ聊天室

小明界面变化

spring boot练习--利用websocket实现QQ聊天室

控制台输出:

spring boot练习--利用websocket实现QQ聊天室spring boot练习--利用websocket实现QQ聊天室

代码部分

pom.xml添加依赖
<dependency>

    <groupId>com.alibaba</groupId>

    <artifactId>fastjson</artifactId>

    <version>1.2.47</version>

</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
  </dependency>
User.java
public class User {
    private String userId;
    private String userName;
    private int userImg;
    private Msg userMsg;

    public int getUserImg() {
        return userImg;
    }

    public void setUserImg(int userImg) {
        this.userImg = userImg;
    }

    public User(String userId, String userName, int userImg) {
        this.userId = userId;
        this.userName = userName;
        this.userImg = userImg;
    }

    public User() {
    }

    public User(String userId, String userName) {
        this.userId = userId;
        this.userName = userName;
    }

    public User(String userId, String userName, Msg userMsg) {
        this.userId = userId;
        this.userName = userName;
        this.userMsg = userMsg;
    }

    public User(String userId, String userName, int userImg, Msg userMsg) {
        this.userId = userId;
        this.userName = userName;
        this.userImg = userImg;
        this.userMsg = userMsg;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Msg getUserMsg() {
        return userMsg;
    }

    public void setUserMsg(Msg userMsg) {
        this.userMsg = userMsg;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
Msg.java
public class Msg {
    private boolean send;//是否是发送的消息
    private String content;//发送的内容
    private boolean system;//是否是系统消息

    public Msg(boolean send, String content) {
        this.send = send;
        this.content = content;
        this.system = false;
    }

    public Msg() {
    }

    public Msg(boolean send, String content, boolean system) {
        this.send = send;
        this.content = content;
        this.system = system;
    }

    public boolean isSystem() {
        return system;
    }

    public void setSystem(boolean system) {
        this.system = system;
    }



    public boolean isSend() {
        return send;
    }

    public void setSend(boolean send) {
        this.send = send;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
WebSocketTest.java
@ServerEndpoint("/test/{userId}")
@Component
public class WebSocketTest {
    /**
     * 存放所有在线的客户端
     */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();
    private String userId;

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        System.out.println("打开了一个连接");
        System.out.println("userId:"+userId);
        System.out.println("session.getId():"+session.getId());
        this.userId = userId;

        User user = new User();
        user.setUserMsg(new Msg(false,"有新人加入聊天",true));
        sendAll(user.toString());

        //将新用户存入在线的组
        clients.put(userId, session);
    }

    /**
     * 客户端关闭
     * @param session session
     */
    @OnClose
    public void onClose(Session session, @PathParam("userId") String userId) {
        System.out.println("有用户断开了");
        System.out.println("userId:"+userId);
        System.out.println("session.getId():"+session.getId());

        User user = new User();
        user.setUserMsg(new Msg(false,"有用户断开聊天",true));
        sendAll(user.toString());

        //将掉线的用户移除在线的组里
        clients.remove(userId);
    }

    /**
     * 发生错误
     * @param throwable e
     */
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * 收到客户端发来消息
     * @param message  消息对象
     */
    @OnMessage
    public void onMessage(String message) {
        System.out.println("服务端收到客户端发来的消息:"+message);
        User user = JSON.parseObject(message, User.class);
        user.getUserMsg().setSend(false);

        this.sendAll(user.toString());
    }

    /**
     * 群发消息
     * @param message 消息内容
     */
    private void sendAll(String message) {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            if (!sessionEntry.getKey().equals(userId)){
                sessionEntry.getValue().getAsyncRemote().sendText(message);
            }
        }
    }
}
WebSocketConfig.java
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}
相关标签: spring boot