前言
websocket概述:
在日常的web应用开发中,常见的是前端向后端发起请求,有些时候会涉及到前后端互发消息,这时候就用到了websocket。
一、websocket原理
websocket是一种在单个tcp连接上进行全双工通信的协议。它通过一个简单的握手过程来建立连接,然后在连接上进行双向数据传输。与传统的http请求不同,websocket连接一旦建立,就可以在客户端和服务器之间保持打开状态,直到被任何一方关闭。
核心特点包括:
- 全双工通信:客户端和服务器可以同时发送和接收消息。
- 持久连接:一旦建立连接,就可以持续进行数据交换,无需像http那样频繁地建立新的连接。
- 低延迟:由于连接是持久的,数据可以几乎实时地发送和接收。
- 轻量级协议:websocket协议的头部信息非常简单,减少了数据传输的开销。
二、spring boot集成websocket
代码结构:

2.1. 引入依赖
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-websocket</artifactid>
</dependency>
2.2 配置类websocketconfig
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.web.socket.server.standard.serverendpointexporter;
import org.springframework.web.socket.server.standard.servletservercontainerfactorybean;
/**
* websocket配置类。
* 用于启用spring websocket支持,通过@bean注解注册serverendpointexporter,
* 从而允许使用@serverendpoint注解定义websocket端点。
*/
@configuration
public class websocketconfig {
/**
* 注册serverendpointexporter bean。
* serverendpointexporter是spring提供的一个工具类,
* 它会扫描并注册所有使用@serverendpoint注解的类为websocket端点。
*
* @return serverendpointexporter实例
*/
@bean
public serverendpointexporter serverendpointexporter() {
return new serverendpointexporter();
}
/**
* 通信文本消息和二进制缓存区大小
* 避免报文过大时,websocket 1009 错误
*/
@bean
public servletservercontainerfactorybean createwebsocketcontainer() {
servletservercontainerfactorybean container = new servletservercontainerfactorybean();
// 文本/二进制消息最大缓冲区(10mb)
container.setmaxtextmessagebuffersize(1024 * 1024 * 10);
container.setmaxbinarymessagebuffersize(1024 * 1024 * 10);
// 最大会话空闲超时时间(1小时)
container.setmaxsessionidletimeout(60 * 60 * 1000l);
return container;
}
}
2.3 websocketserver 类
websocketserver 类实现了 websocket 服务端的功能。 负责处理 websocket 连接的建立、关闭、消息接收和发送等操作。
import lombok.getter;
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.objects;
import java.util.concurrent.copyonwritearrayset;
/**
* websocketserver 类实现了 websocket 服务端的功能。
* 它负责处理 websocket 连接的建立、关闭、消息接收和发送等操作。
*/
@component
@slf4j
@serverendpoint("/api/websocket/{sid}")
public class websocketserver {
// 静态变量,用于记录当前在线连接数
private static int onlinecount = 0;
// 存储所有连接的 websocketserver 实例
@getter
private static final copyonwritearrayset<websocketserver> websocketset = new copyonwritearrayset<>();
// 当前连接的会话对象
private session session;
// 客户端唯一标识符
private string sid = "";
/**
* 连接建立成功时调用的方法。
*
* @param session 当前连接的会话对象
* @param sid 客户端唯一标识符
*/
@onopen
public void onopen(session session, @pathparam("sid") string sid) {
this.session = session;
websocketset.add(this); // 将当前实例加入集合
this.sid = sid;
addonlinecount(); // 在线数加1
try {
sendmessage("websocket 连接成功"); // 发送连接成功的消息
log.info("有新窗口开始监听:{},当前在线人数为:{}", sid, getonlinecount());
} catch (ioexception e) {
log.error("websocket io exception");
}
}
/**
* 连接关闭时调用的方法。
*/
@onclose
public void onclose() {
websocketset.remove(this); // 从集合中移除当前实例
subonlinecount(); // 在线数减1
log.info("释放的sid为:{}", sid);
log.info("有一个连接关闭!当前在线人数为{}", getonlinecount());
}
/**
* 接收到客户端消息时调用的方法。
*
* @param message 客户端发送的消息
* @param session 当前连接的会话对象
*/
@onmessage
public void onmessage(string message, session session) {
log.info("收到来自窗口{}的信息:{}", sid, message);
// 群发消息
for (websocketserver item : websocketset) {
if (objects.equals(item.sid, this.sid)) {
continue;
}
sendmessagetoclient(item, message);
}
}
/**
* 实现服务器主动推送消息的方法,并统一处理异常。
*
* @param client 要推送的客户端实例
* @param message 要推送的消息
*/
private void sendmessagetoclient(websocketserver client, string message) {
try {
client.sendmessage(message);
} catch (ioexception e) {
log.error("向客户端 {} 发送消息时出错: {}", client.sid, message, e);
}
}
/**
* 群发自定义消息给指定的客户端。
*
* @param message 要发送的消息
* @param sid 客户端唯一标识符,为 null 时发送给所有客户端
* @throws ioexception 如果发送消息时发生 i/o 错误
*/
public static void sendinfo(string message, @pathparam("sid") string sid) throws ioexception {
log.info("推送消息到窗口" + sid + ",推送内容:" + message);
for (websocketserver item : websocketset) {
try {
if (sid == null) {
// 如果 sid 为 null,则发送给所有客户端
item.sendmessage(message);
} else if (item.sid.equals(sid)) {
// 如果 sid 匹配,则只发送给该客户端
item.sendmessage(message);
}
} catch (ioexception e) {
log.error("向客户端 {} 发送消息时出错: {}", item.sid, message, e);
}
}
}
/**
* 发生错误时调用的方法。
*
* @param session 当前连接的会话对象
* @param error 发生的错误
*/
@onerror
public void onerror(session session, throwable error) {
log.error("发生错误");
error.printstacktrace();
}
/**
* 实现服务器主动推送消息的方法。
*
* @param message 要推送的消息
* @throws ioexception 如果发送消息时发生 i/o 错误
*/
public void sendmessage(string message) throws ioexception {
this.session.getbasicremote().sendtext(message);
}
/**
* 获取当前在线连接数。
*
* @return 当前在线连接数
*/
public static synchronized int getonlinecount() {
return onlinecount;
}
/**
* 增加在线连接数。
*/
public static synchronized void addonlinecount() {
websocketserver.onlinecount++;
}
/**
* 减少在线连接数。
*/
public static synchronized void subonlinecount() {
websocketserver.onlinecount--;
}
}
2.4 前端代码 index.html
<!doctype html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<title>websocket 聊天室</title>
<script src="https://autherp.jd.com/js/jquery.js"></script>
<style>
.time {
font-size: 0.8em;
display: block;
margin-bottom: 5px;
}
.user-msg {
background-color: #90ee90;
padding: 8px;
border-radius: 8px;
max-width: 70%;
display: inline-block;
}
.system-msg {
background-color: #d3d3d3;
padding: 8px;
border-radius: 8px;
max-width: 70%;
display: inline-block;
font-size: 0.9em;
}
#message-box {
height: 300px;
overflow-y: auto;
margin-bottom: 10px;
border: 1px solid #ccc;
padding: 10px;
border-radius: 4px;
}
.message-right {
text-align: right;
margin: 10px 0;
}
.message-left {
text-align: left;
margin: 10px 0;
}
.message-center {
text-align: center;
margin: 10px 0;
}
.container {
max-width: 600px;
margin: 20px auto;
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.input-group {
display: flex;
gap: 10px;
}
.input-group input[type="text"] {
flex-grow: 1;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
.btn-primary, .btn-danger {
padding: 8px 16px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.btn-primary {
background-color: #007bff;
color: white;
}
.btn-primary:hover {
background-color: #0056b3;
}
.btn-danger {
background-color: #dc3545;
color: white;
}
.btn-danger:hover {
background-color: #c82333;
}
/* 添加新样式让标题和按钮居中 */
.container h2,
.container .btn-danger {
text-align: center;
display: block;
margin-left: auto;
margin-right: auto;
}
/* 为按钮添加一些外边距,使其看起来更美观 */
.container .btn-danger {
margin-top: 10px;
}
</style>
</head>
<body>
<div class="container">
<h2>websocket 聊天室</h2>
<!-- 添加显示 sid 的元素 -->
<p id="sid-display">当前用户 sid: <span id="sid-value"></span></p>
<!-- 消息显示区域 -->
<div id="message-box"></div>
<!-- 输入框与发送按钮 -->
<div class="input-group">
<input type="text" id="text" placeholder="请输入消息..." />
<button class="btn-primary" onclick="send()">发送</button>
</div>
<hr/>
<!-- 关闭连接按钮 -->
<button class="btn-danger" onclick="closewebsocket()">关闭 websocket 连接</button>
</div>
<script type="text/javascript">
let websocket = '';
// 获取当前页面 url 中的 sid 参数或随机生成一个
function getsid() {
const urlparams = new urlsearchparams(window.location.search);
return urlparams.get('sid') || math.floor(1000 + math.random() * 9000); // 4位数字
}
const sid = getsid();
const wsurl = `ws://127.0.0.1:9999/api/websocket/${sid}`;
// 页面加载完成后更新 sid 显示
window.onload = function() {
document.getelementbyid('sid-value').textcontent = sid;
};
// 初始化 websocket
if ('websocket' in window) {
websocket = new websocket(wsurl);
} else {
alert('当前浏览器不支持 websocket');
}
// 连接成功
websocket.onopen = function () {
console.log('websocket 连接成功');
};
// 接收消息
websocket.onmessage = function (event) {
addmessage(event.data);
};
// 错误处理
websocket.onerror = function () {
console.log('websocket 连接发生错误');
};
// 关闭连接
websocket.onclose = function () {
this.closewebsocket();
console.log('websocket 连接已关闭');
};
// 页面关闭前断开连接
window.onbeforeunload = function () {
this.closewebsocket();
};
// 发送消息
function send() {
let message = document.getelementbyid('text').value.trim();
if (!message) return;
if (websocket && websocket.readystate === websocket.open) {
websocket.send(`{"msg":"${message}","sid":"${sid}", "time": "${new date().tolocaletimestring()}"}`);
addmessage(`{"msg":"${message}","sid":"${sid}", "time": "${new date().tolocaletimestring()}"}`);
document.getelementbyid('text').value = '';
} else {
addmessage("websocket 连接未建立,请稍后再试。");
}
}
//关闭websocket连接
function closewebsocket() {
if (websocket) {
websocket.close();
}
}
// 添加消息到聊天区
function addmessage(content) {
let msgbox = document.getelementbyid('message-box');
const time = new date().tolocaletimestring();
const div = document.createelement('div');
let messagedata;
let issystemmessage = false;
try {
messagedata = json.parse(content);
} catch (e) {
issystemmessage = true;
}
if (issystemmessage) {
div.classname = 'message-center';
div.innerhtml = `
<span class="time">${time}</span>
<span class="system-msg"> ${content}</span>
`;
} else {
const ismymessage = string(messagedata.sid) === string(sid);
div.classname = ismymessage ? 'message-right' : 'message-left';
div.innerhtml = `
<span class="time">${messagedata.time}</span>
<span class="${ismymessage ? 'user-msg' : 'system-msg'}">
${ismymessage ? '' : '用户#' + messagedata.sid + ':'} ${messagedata.msg}
</span>
`;
}
msgbox.appendchild(div);
msgbox.scrolltop = msgbox.scrollheight;
}
</script>
</body>
</html>
2.5 controller访问首页
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
@controller
public class testcontroller {
@requestmapping("/")
public string index(){
return "index.html";
}
}
打开多个网页窗口,访问ip:端口


到此这篇关于springboot整合websocket 实现聊天室功能的文章就介绍到这了,更多相关springboot websocket聊天室内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论