SpringBoot+WebSocket群聊功能完整代码实例
  0ZwfR6X6Muxs 2023年11月26日 30 0



这里写自定义目录标题

  • 效果图
  • 准备条件
  • 配置类
  • WebSocket相应类
  • 前端代码


效果图

每一个浏览器打开都会生成一个随机数,当然你也可以通过ip来控制,目的是实现即时通讯的功能.
接下来的代码都是全部的代码,你可以直接拿过来用就行.终极目的是通过简单示例了解他的沟通过程
目前是群发广播,如果想要实现一对一聊天的话,就需要记录userid来区分用户进行广播.也就是点对点的即时通讯.入门建议先走一遍群发广播.

SpringBoot+WebSocket群聊功能完整代码实例_websocket

准备条件

Java首先引入maven-版本根据你的spring-boot版本就行

<!--websocket 即时通讯-->
<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

配置类

准备config类直接复制就行

import org.springframework.context.annotation.Bean;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @author hanfeng
 * @date 2022/1/14
 */
@Component
public class WebSocketAutoConfig {

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

}

WebSocket相应类

此部分是从网上复制过来的比较简单,但我这个是用的jwt令牌鉴权的,所以还需要再写一套鉴权的过程代码,此处只是简单实现.

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author hanfeng
 * @date 2022/1/19
 */
@Component
@ServerEndpoint ("/webSocket")
@Slf4j
public class WebSocket {

    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        //这里就是我们所提交的token
        //String submitedToken=session.getHandshakeHeaders().get("sec-websocket-protocol").get(0);
        webSocketSet.add(this);
        this.sendMessage("第一次回应消息");
        log.info("【websocket消息】有新的连接, 总数:{}", webSocketSet.size());
    }
    //
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        log.info("【websocket消息】连接断开, 总数:{}", webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("【websocket消息】收到客户端发来的消息:{}", message);
        this.sendMessage(message);
    }

    public void sendMessage(String message) {
        for (WebSocket webSocket : webSocketSet) {
            log.info("【websocket消息】广播消息, message={}", message);
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

前端代码

前端代码之前不是这样,我做了一个小小的完善.

<html>
<head>
    <meta charset="UTF-8">
    <title>websocket测试</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <style type="text/css">
        h3,h4{
            text-align:center;
        }
		#messageId{
			width:1070px;
			height:500px;
			margin:0 auto;
			border:1px solid #e5e5e5;
			  background: #ece9e6;
			  background: -webkit-linear-gradient(to bottom, #ffffff, #ece9e6); 
			  background: linear-gradient(to bottom, #ffffff, #ece9e6);
			padding:10px;
			overflow-y:auto;
		}
		#messageId p{
			margin-bottom:8px;
		}
		.wby{
			height:60px;
			resize:none;
			margin-top:10px;
			padding:10px;
		}
		.shuru{
			position:relative;
			width:1090px;
			margin:0 auto;
		}
		.sendMsg{
			position:absolute;
			right:5px;
			bottom:5px;
			width:60px;
			height:25px;
			line-height:25px;
			border:none;
			background-color:green;
			color:#fff;
			border-radius:5px;
		}
    </style>
</head>
<body>

<h3>WebSocket小组聊天室</h3>

<div id = "messageId"></div>
<form onsubmit="return false" action="##" id="formtest">
	<div class="shuru">
		<textarea class="wby" name="msg" cols="150" value="" onkeypress="BindEnter();"></textarea>
		<input class="sendMsg" type="button" value="发送" onclick="sendMessage()" >
	</div>
</form>

<script type="text/javascript" >
    var socket;
	var ceil = Math.ceil(Math.random()*10);
    if (typeof (WebSocket) == "undefined") {
        console.log("遗憾:您的浏览器不支持WebSocket");
    } else {
        console.log("恭喜:您的浏览器支持WebSocket");
        //实现化WebSocket对象
        //指定要连接的服务器地址与端口建立连接
        //注意ws、wss使用不同的端口。我使用自签名的证书测试,
        //无法使用wss,浏览器打开WebSocket时报错
        //ws对应http、wss对应https。
        socket = new WebSocket("ws://127.0.0.1:80/webSocket");
        //连接打开事件
        socket.onopen = function() {
            console.log("Socket 已打开");
            socket.send('<p style="color:#999;text-align:center;font-size:3px">'+ceil+"号:加入群聊"+'</p>');
        };
        //收到消息事件
        socket.onmessage = function(msg) {
            $("#messageId").append('<p style="font-size:15px">'+ msg.data+'</p>');
            console.log(msg.data);
        };
		 //发送消息事件
        socket.sendMessage = function(msg) {
			socket.send(ceil+"号: "+msg);
            $(".wby").val('');
        };
        //连接关闭事件
        socket.onclose = function() {
            console.log("Socket已关闭");
        };
        //发生了错误事件
        socket.onerror = function() {
            alert("Socket发生了错误");
        }
        //窗口关闭时,关闭连接
        window.unload=function() {
            socket.close();
        };
    }
	
	function sendMessage() {
		var msg = $("textarea[name='msg']").val();
		socket.sendMessage(msg);
	}
	
	function BindEnter(e){
		var evt  = window.event || e;
		if(evt.keyCode == 13){
			//回车事件
			var msg = $("textarea[name='msg']").val();
			socket.sendMessage(msg);
		}
	}
</script>

</body>
</html>


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月26日 0

暂无评论

推荐阅读
  2Vtxr3XfwhHq   2024年05月17日   53   0   0 Java
  Tnh5bgG19sRf   2024年05月20日   109   0   0 Java
  8s1LUHPryisj   2024年05月17日   46   0   0 Java
  aRSRdgycpgWt   2024年05月17日   47   0   0 Java
0ZwfR6X6Muxs