Springboot实现WebSocket群聊简单demo

前言:

这里不做springboot框架搭建步骤,只做具体的实现,代码里有具体注释,所以不做多解释这里。
代码里可能有相关日志的输出用到了slf4j,可以删掉改成System.out.println();看自己喜好。

在这里插入图片描述
在这里插入图片描述

1、引入WebSocket依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

2、写入WebSocket配置类

在这里插入图片描述

package com.xuan.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * WebSocket配置类
 * @author Xuan
 * @date 2020/1/3 16:49
 */
@Configuration
public class WebSocketConfig {
    //实例化一个Bean对象
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3、写入WebSocket群聊Controller控制层

在这里插入图片描述

package com.xuan.servlet.backend;

import lombok.extern.slf4j.Slf4j;
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.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Xuan
 * @date 2020/1/4 11:18
 */
@Slf4j
@Component
@ServerEndpoint("/groupChat/{Group_no}/{username}")
public class GroupChatController {
    // 保存 组id->组成员 的映射关系 之所以使用ConcurrentHashMap因为这个是线程安全的,里面采用了分段锁而HashMap是线程不安全的
    private static ConcurrentHashMap<String, List<Session>> groupMemberInfoMap = new ConcurrentHashMap<>();

    // 收到消息调用的方法,群成员发送消息
    @OnMessage
    public void onMessage(@PathParam("Group_no") String Group_no,
                          @PathParam("username") String username, String message) {
        //得到当前群的所有会话,也就是所有用户
        List<Session> sessionList = groupMemberInfoMap.get(Group_no);
        // 遍历Session集合给每个会话发送文本消息
        sessionList.forEach(item -> {
            try {
                String text = username + ": " + message;
                item.getBasicRemote().sendText(text);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 建立连接调用的方法,群成员加入
     * @param session 会话
     * @param Group_no 群id
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("Group_no") String Group_no) {
        //得到当前群的所有会话,也就是所有用户
        List<Session> sessionList = groupMemberInfoMap.get(Group_no);
        if (sessionList == null) {
            sessionList = new ArrayList<>();
            groupMemberInfoMap.put(Group_no,sessionList);
        }
        sessionList.add(session);
        log.info("连接建立");
        log.info("群号: {}, 群人数: {}", Group_no, sessionList.size());
    }

    // 关闭连接调用的方法,群成员退出
    @OnClose
    public void onClose(Session session, @PathParam("Group_no") String Group_no) {
        List<Session> sessionList = groupMemberInfoMap.get(Group_no);
        sessionList.remove(session);
        log.info("连接关闭");
        log.info("群号: {}, 群人数: {}", Group_no, sessionList.size());
    }

    // 传输消息错误调用的方法
    @OnError
    public void OnError(Throwable error) {
        log.info("连接出错:{}",error.getMessage());
    }
}

4、前端html,注释是全套的,自己一边用一边理解

在这里插入图片描述

<!DOCTYPE html>
<html>
<head>
    <title>测试WebSocket</title>
</head>
<body>
<div>
	
</div>
<center>
<div>
	<h1>WebSocket群聊</h1>
	<input type="text" id="Group_no" placeholder="请输入房间号"/><br>
	<input type="text" id="nickname" placeholder="请输入昵称"/><br>
	<input type="submit" value="连接" onclick="connect()" /><br>
	<textarea rows="3" cols="20" id="content"></textarea><br>
	<input type="submit" value="发送" onclick="start()" />
    <br>
</div>
<div id="messages"></div>
</center>
<script type="text/javascript">
    var webSocket = null;
	//收到消息
    function onMessage(event) {
        document.getElementById('messages').innerHTML
            += '<br />' + event.data;
    }
	//建立连接
    function onOpen(event) {
        document.getElementById('messages').innerHTML
            = '连接已经建立';
    }
	//发生错误
    function onError(event) {
        alert("发生错误");
		webSocket = null;
    }
	//连接关闭
    function onClose(event) {
        alert("连接关闭");
		webSocket = null;
    }
	//连接
    function connect() {
		//获取群号
        var Group_no = document.getElementById('Group_no').value;
		//获取昵称
        var nickname = document.getElementById('nickname').value;
		//验证非法数据
        if (url == '' || nickname == '') {
            alert("群号和用户名不能为空");
            return;
        }
		//验证是否已经建立连接
		if(webSocket!=null){
			alert("已经建立过连接,如需重新建立连接,请自行更改逻辑,或者重新刷新页面");
			return; 
		}
		//创建Websocket连接url
        var url = 'ws://localhost:8080/groupChat/' + Group_no + '/' + nickname;
		//实例化WebSocket
        webSocket = new WebSocket(url);
		//出现错误
        webSocket.onerror = function(event) {
            onError(event)
        };
		//调用创建连接
        webSocket.onopen = function(event) {
            onOpen(event)
        };
		//调用收到消息
        webSocket.onmessage = function(event) {
            onMessage(event)
        };
		//调用关闭连接
        webSocket.onclose = function(event) {
            onClose(event)
        };
    }
	//开始发送
    function start() {
		//获取发送的内容
        var text = document.getElementById('content').value;
		if(text== ''){
			alert("发送内容不允许为空");
			return;
		}
		if(webSocket==null){
			alert("请先建立连接");
			return;
		}
		//调用WebSocket发送的方法
        webSocket.send(text);
		//初始化文本域的内容为空
        document.getElementById('content').value = '';
    }
</script>
</body>
</html>

5、如果连接失败或者出错,请确定后端已经启动项目,并且可以访问对应的路径。

在这里插入图片描述

6、遇到困难可以评论(有信必回)小轩微信17382121839

发布了47 篇原创文章 · 获赞 57 · 访问量 8861

猜你喜欢

转载自blog.csdn.net/qq_41741884/article/details/103832925