Skip to content
体验新版
项目
组织
正在加载...
登录
切换导航
打开侧边栏
Kwan的解忧杂货铺@新空间代码工作室
SpringBoot-kwan
提交
39954353
S
SpringBoot-kwan
项目概览
Kwan的解忧杂货铺@新空间代码工作室
/
SpringBoot-kwan
通知
2
Star
0
Fork
0
代码
文件
提交
分支
Tags
贡献者
分支图
Diff
Issue
0
列表
看板
标记
里程碑
合并请求
0
DevOps
流水线
流水线任务
计划
Wiki
0
Wiki
分析
仓库
DevOps
项目成员
Pages
S
SpringBoot-kwan
项目概览
项目概览
详情
发布
仓库
仓库
文件
提交
分支
标签
贡献者
分支图
比较
Issue
0
Issue
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
Pages
DevOps
DevOps
流水线
流水线任务
计划
分析
分析
仓库分析
DevOps
Wiki
0
Wiki
成员
成员
收起侧边栏
关闭侧边栏
动态
分支图
创建新Issue
流水线任务
提交
Issue看板
提交
39954353
编写于
8月 26, 2023
作者:
Kwan的解忧杂货铺@新空间代码工作室
🐭
浏览文件
操作
浏览文件
下载
电子邮件补丁
差异文件
fix:添加websocket收发消息
上级
e6fc12cd
变更
9
隐藏空白更改
内联
并排
Showing
9 changed file
with
150 addition
and
201 deletion
+150
-201
pom.xml
pom.xml
+6
-0
src/main/java/com/kwan/springbootkwan/SpringBootKwanApplication.java
...va/com/kwan/springbootkwan/SpringBootKwanApplication.java
+2
-0
src/main/java/com/kwan/springbootkwan/config/WebSocketConfig.java
.../java/com/kwan/springbootkwan/config/WebSocketConfig.java
+1
-1
src/main/java/com/kwan/springbootkwan/controller/SystemController.java
.../com/kwan/springbootkwan/controller/SystemController.java
+0
-40
src/main/java/com/kwan/springbootkwan/filter/TimeFilter.java
src/main/java/com/kwan/springbootkwan/filter/TimeFilter.java
+1
-1
src/main/java/com/kwan/springbootkwan/service/WebSocketServer.java
...java/com/kwan/springbootkwan/service/WebSocketServer.java
+42
-97
src/main/resources/application.yaml
src/main/resources/application.yaml
+1
-1
src/main/resources/index.html
src/main/resources/index.html
+23
-61
src/main/resources/templates/socket1.html
src/main/resources/templates/socket1.html
+74
-0
未找到文件。
pom.xml
浏览文件 @
39954353
...
...
@@ -221,6 +221,12 @@
<artifactId>
spring-boot-starter-websocket
</artifactId>
<version>
2.6.6
</version>
</dependency>
<!-- thymeleaf依赖 -->
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-thymeleaf
</artifactId>
<version>
3.1.2
</version>
</dependency>
</dependencies>
<build>
<plugins>
...
...
src/main/java/com/kwan/springbootkwan/SpringBootKwanApplication.java
浏览文件 @
39954353
...
...
@@ -4,8 +4,10 @@ import org.springframework.batch.core.configuration.annotation.EnableBatchProces
import
org.springframework.boot.SpringApplication
;
import
org.springframework.boot.autoconfigure.SpringBootApplication
;
import
org.springframework.scheduling.annotation.EnableScheduling
;
import
org.springframework.web.socket.config.annotation.EnableWebSocket
;
import
springfox.documentation.swagger2.annotations.EnableSwagger2
;
@EnableWebSocket
@EnableSwagger2
@EnableScheduling
@EnableBatchProcessing
...
...
src/main/java/com/kwan/springbootkwan/config/WebSocketConfig.java
浏览文件 @
39954353
...
...
@@ -4,7 +4,6 @@ import org.springframework.context.annotation.Bean;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.web.socket.server.standard.ServerEndpointExporter
;
/**
* 开启websocket的支持
*
...
...
@@ -12,6 +11,7 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter;
* @version : 2.2.0
* @date : 2023/8/26 16:45
*/
@Configuration
public
class
WebSocketConfig
{
@Bean
...
...
src/main/java/com/kwan/springbootkwan/controller/SystemController.java
已删除
100644 → 0
浏览文件 @
e6fc12cd
package
com.kwan.springbootkwan.controller
;
import
com.kwan.springbootkwan.service.WebSocketServer
;
import
org.springframework.stereotype.Controller
;
import
org.springframework.web.bind.annotation.GetMapping
;
import
org.springframework.web.bind.annotation.PathVariable
;
import
org.springframework.web.bind.annotation.RequestMapping
;
import
org.springframework.web.bind.annotation.ResponseBody
;
import
org.springframework.web.servlet.ModelAndView
;
import
java.io.IOException
;
import
java.util.HashMap
;
import
java.util.Map
;
@Controller
(
"web_Scoket_system"
)
@RequestMapping
(
"/api/socket"
)
public
class
SystemController
{
//页面请求
@GetMapping
(
"/index/{userId}"
)
public
ModelAndView
socket
(
@PathVariable
String
userId
)
{
ModelAndView
mav
=
new
ModelAndView
(
"/socket1"
);
mav
.
addObject
(
"userId"
,
userId
);
return
mav
;
}
//推送数据接口
@ResponseBody
@RequestMapping
(
"/socket/push/{cid}"
)
public
Map
pushToWeb
(
@PathVariable
String
cid
,
String
message
)
{
Map
<
String
,
Object
>
result
=
new
HashMap
<>();
try
{
WebSocketServer
.
sendInfo
(
message
,
cid
);
result
.
put
(
"code"
,
cid
);
result
.
put
(
"msg"
,
message
);
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
return
result
;
}
}
src/main/java/com/kwan/springbootkwan/filter/TimeFilter.java
浏览文件 @
39954353
...
...
@@ -18,7 +18,7 @@ public class TimeFilter implements Filter {
@Override
public
void
doFilter
(
ServletRequest
request
,
ServletResponse
response
,
FilterChain
chain
)
throws
IOException
,
ServletException
{
log
.
info
(
"先执行:接口执行时间"
);
//
log.info("先执行:接口执行时间");
chain
.
doFilter
(
request
,
response
);
}
}
...
...
src/main/java/com/kwan/springbootkwan/service/WebSocketServer.java
浏览文件 @
39954353
package
com.kwan.springbootkwan.service
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.stereotype.Component
;
import
javax.websocket.OnClose
;
...
...
@@ -8,126 +7,72 @@ import javax.websocket.OnError;
import
javax.websocket.OnMessage
;
import
javax.websocket.OnOpen
;
import
javax.websocket.Session
;
import
javax.websocket.server.PathParam
;
import
javax.websocket.server.ServerEndpoint
;
import
java.io.IOException
;
import
java.text.SimpleDateFormat
;
import
java.util.Date
;
import
java.util.concurrent.CopyOnWriteArraySet
;
@Component
@Slf4j
@ServerEndpoint
(
value
=
"/api/websocket/{sid}"
)
@ServerEndpoint
(
"/websocket"
)
public
class
WebSocketServer
{
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private
static
int
onlineCount
=
0
;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private
static
CopyOnWriteArraySet
<
WebSocketServer
>
webSocketSet
=
new
CopyOnWriteArraySet
<>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
//准备一个内部安全的集合 存放所有用户的websocket服务
private
static
CopyOnWriteArraySet
<
WebSocketServer
>
wsset
=
new
CopyOnWriteArraySet
<>();
private
Session
session
;
//接收sid
private
String
sid
=
""
;
/**
* 连接建立成功调用的方法
*/
@OnOpen
public
void
o
nOpen
(
Session
session
,
@PathParam
(
"sid"
)
String
sid
)
{
public
void
o
pOpen
(
Session
session
)
{
this
.
session
=
session
;
webSocketSet
.
add
(
this
);
//加入set中
this
.
sid
=
sid
;
addOnlineCount
();
//在线数加1
try
{
sendMessage
(
"conn_success"
);
log
.
info
(
"有新窗口开始监听:"
+
sid
+
",当前在线人数为:"
+
getOnlineCount
());
}
catch
(
IOException
e
)
{
log
.
error
(
"websocket IO Exception"
);
}
}
//将自身填充到set集合中 这个集合是所有客户端websocket的集合
wsset
.
add
(
this
);
// sendMsg();
/**
* 连接关闭调用的方法
*/
@OnClose
public
void
onClose
()
{
webSocketSet
.
remove
(
this
);
//从set中删除
subOnlineCount
();
//在线数减1
//断开连接情况下,更新主板占用情况为释放
log
.
info
(
"释放的sid为:"
+
sid
);
//这里写你 释放的时候,要处理的业务
log
.
info
(
"有一连接关闭!当前在线人数为"
+
getOnlineCount
());
}
/**
* 收到客户端消息后调用的方法
*
* @ Param message 客户端发送过来的消息
*/
@OnMessage
public
void
onMessage
(
String
message
,
Session
session
)
{
log
.
info
(
"收到来自窗口"
+
sid
+
"的信息:"
+
message
);
//群发消息
for
(
WebSocketServer
item
:
webSocketSet
)
{
try
{
item
.
sendMessage
(
message
);
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
}
@OnClose
public
void
onClose
()
{
//将自己从set集合中删除
wsset
.
remove
(
this
);
}
/**
* @ Param session
* @ Param error
*/
@OnError
public
void
onError
(
Session
session
,
Throwable
error
)
{
log
.
error
(
"发生错误"
);
error
.
printStackTrace
();
System
.
out
.
println
(
this
+
"发生错误了"
);
}
/**
* 实现服务器主动推送
*/
public
void
sendMessage
(
String
message
)
throws
IOException
{
this
.
session
.
getBasicRemote
().
sendText
(
message
);
//客户端发来消息
@OnMessage
public
void
onMessage
(
String
clientMsg
,
Session
session
)
{
System
.
out
.
println
(
"来自客户端的信息+“。。。。。。。。。”===》"
+
clientMsg
);
//每隔一秒给你推送一条当前时间信息
sendAllClient
(
clientMsg
);
}
/**
* 群发自定义消息
*/
public
static
void
sendInfo
(
String
message
,
@PathParam
(
"sid"
)
String
sid
)
throws
IOException
{
log
.
info
(
"推送消息到窗口"
+
sid
+
",推送内容:"
+
message
);
for
(
WebSocketServer
item
:
webSocketSet
)
{
try
{
//这里可以设定只推送给这个sid的,为null则全部推送
if
(
sid
==
null
)
{
// item.sendMessage(message);
}
else
if
(
item
.
sid
.
equals
(
sid
))
{
item
.
sendMessage
(
message
);
}
}
catch
(
IOException
e
)
{
continue
;
private
void
sendMsg
()
{
try
{
while
(
true
)
{
SimpleDateFormat
sdf
=
new
SimpleDateFormat
(
"yyyy-MM-dd HH:mm:ss"
);
String
time
=
sdf
.
format
(
new
Date
());
//发送数据
this
.
session
.
getBasicRemote
().
sendText
(
time
);
Thread
.
sleep
(
1000
);
}
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
catch
(
InterruptedException
e
)
{
e
.
printStackTrace
();
}
}
public
static
synchronized
int
getOnlineCount
()
{
return
onlineCount
;
}
public
static
synchronized
void
addOnlineCount
()
{
WebSocketServer
.
onlineCount
++;
}
public
static
synchronized
void
subOnlineCount
()
{
WebSocketServer
.
onlineCount
--;
}
public
static
CopyOnWriteArraySet
<
WebSocketServer
>
getWebSocketSet
()
{
return
webSocketSet
;
private
void
sendAllClient
(
String
msg
)
{
try
{
for
(
WebSocketServer
wss
:
wsset
)
{
wss
.
session
.
getBasicRemote
().
sendText
(
msg
);
}
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
}
}
}
\ No newline at end of file
src/main/resources/application.yaml
浏览文件 @
39954353
server
:
port
:
8
888
port
:
8
080
servlet
:
encoding
:
force
:
true
...
...
src/main/resources/index.html
浏览文件 @
39954353
<
!DOCTYPE html
>
<
meta
http-equiv=
"Content-Type"
content=
"text/html;charset=utf-8"
/
>
<html>
<head>
<meta
charset=
"utf-8"
>
<title>
Java后端WebSocket的Tomcat实现
</title>
<script
type=
"text/javascript"
src=
"js/jquery.min.js"
></script>
</head>
<body>
<div
id=
"main"
style=
"width: 1200px;height:800px;"
></div>
Welcome
<br/><input
id=
"text"
type=
"text"
/>
<button
onclick=
"send()"
>
发送消息
</button>
<hr/>
<button
onclick=
"closeWebSocket()"
>
关闭WebSocket连接
</button>
<hr/>
<div
id=
"message"
></div>
</body>
<div
id=
"time"
>
只是接受消息的地方
</div>
<input
type=
"text"
id=
"txtMsg"
/>
<br/>
<button
type=
"button"
onclick=
"sendMsg()"
>
发送消息
</button>
<br/>
<script
type=
"text/javascript"
>
var
websocket
=
null
;
//判断当前浏览器是否支持WebSocket
if
(
'
WebSocket
'
in
window
)
{
//改成你的地址
websocket
=
new
WebSocket
(
"
ws://localhost:8888/api/websocket/100
"
);
}
else
{
alert
(
'
当前浏览器 Not support websocket
'
)
}
//new WebSocket
var
webSocket
=
new
WebSocket
(
"
ws://localhost:8080/websocket
"
);
//连接发生错误的回调方法
websocket
.
onerror
=
function
()
{
setMessageInnerHTML
(
"
WebSocket连接发生错误
"
);
};
//连接成功建立的回调方法
websocket
.
onopen
=
function
()
{
setMessageInnerHTML
(
"
WebSocket连接成功
"
);
}
var
U01data
,
Uidata
,
Usdata
//接收到消息的回调方法
websocket
.
onmessage
=
function
(
event
)
{
console
.
log
(
event
);
setMessageInnerHTML
(
event
);
setechart
()
function
sendMsg
()
{
var
txt
=
document
.
getElementById
(
"
txtMsg
"
).
value
;
console
.
log
(
"
待发送的消息是:
"
+
txt
);
webSocket
.
send
(
txt
);
}
//连接关闭的回调方法
websocket
.
onclose
=
function
()
{
setMessageInnerHTML
(
"
WebSocket连接关闭
"
);
webSocket
.
onopen
=
function
()
{
console
.
log
(
"
连接成功
"
);
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window
.
onbeforeunload
=
function
()
{
closeWebSocket
();
webSocket
.
onclose
=
function
()
{
console
.
log
(
"
连接关闭
"
);
}
//将消息显示在网页上
function
setMessageInnerHTML
(
innerHTML
)
{
document
.
getElementById
(
'
message
'
).
innerHTML
+=
innerHTML
+
'
<br/>
'
;
}
//关闭WebSocket连接
function
closeWebSocket
()
{
websocket
.
close
();
webSocket
.
onerror
=
function
()
{
console
.
log
(
"
连接出错
"
);
}
//发送消息
function
send
()
{
var
message
=
document
.
getElementById
(
'
text
'
).
value
;
websocket
.
send
(
'
{"msg":"
'
+
message
+
'
"}
'
);
setMessageInnerHTML
(
message
+
"
"
);
webSocket
.
onmessage
=
function
(
msg
)
{
console
.
log
(
"
收到的消息是:
"
+
msg
.
data
);
document
.
getElementById
(
"
time
"
).
innerHTML
=
msg
.
data
;
}
</script>
</html>
\ No newline at end of file
</body>
</html>
src/main/resources/templates/socket1.html
0 → 100644
浏览文件 @
39954353
<!DOCTYPE html>
<html>
<head>
<meta
charset=
"utf-8"
>
<title>
Java后端WebSocket的Tomcat实现
</title>
<script
type=
"text/javascript"
src=
"js/jquery.min.js"
></script>
</head>
<body>
<div
id=
"main"
style=
"width: 1200px;height:800px;"
></div>
Welcome
<br/><input
id=
"text"
type=
"text"
/>
<button
onclick=
"send()"
>
发送消息
</button>
<hr/>
<button
onclick=
"closeWebSocket()"
>
关闭WebSocket连接
</button>
<hr/>
<div
id=
"message"
></div>
</body>
<script
type=
"text/javascript"
>
var
websocket
=
null
;
//判断当前浏览器是否支持WebSocket
if
(
'
WebSocket
'
in
window
)
{
//改成你的地址
websocket
=
new
WebSocket
(
"
ws://localhost:8888/api/websocket/100
"
);
}
else
{
alert
(
'
当前浏览器 Not support websocket
'
)
}
//连接发生错误的回调方法
websocket
.
onerror
=
function
()
{
setMessageInnerHTML
(
"
WebSocket连接发生错误
"
);
};
//连接成功建立的回调方法
websocket
.
onopen
=
function
()
{
setMessageInnerHTML
(
"
WebSocket连接成功
"
);
}
var
U01data
,
Uidata
,
Usdata
//接收到消息的回调方法
websocket
.
onmessage
=
function
(
event
)
{
console
.
log
(
event
);
setMessageInnerHTML
(
event
);
setechart
()
}
//连接关闭的回调方法
websocket
.
onclose
=
function
()
{
setMessageInnerHTML
(
"
WebSocket连接关闭
"
);
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window
.
onbeforeunload
=
function
()
{
closeWebSocket
();
}
//将消息显示在网页上
function
setMessageInnerHTML
(
innerHTML
)
{
document
.
getElementById
(
'
message
'
).
innerHTML
+=
innerHTML
+
'
<br/>
'
;
}
//关闭WebSocket连接
function
closeWebSocket
()
{
websocket
.
close
();
}
//发送消息
function
send
()
{
var
message
=
document
.
getElementById
(
'
text
'
).
value
;
websocket
.
send
(
'
{"msg":"
'
+
message
+
'
"}
'
);
setMessageInnerHTML
(
message
+
"
"
);
}
</script>
</html>
\ No newline at end of file
编辑
预览
Markdown
is supported
0%
请重试
或
添加新附件
.
添加附件
取消
You are about to add
0
people
to the discussion. Proceed with caution.
先完成此消息的编辑!
取消
想要评论请
注册
或
登录