- ubuntu12.04环境下使用kvm ioctl接口实现最简单的虚拟机
- Ubuntu 通过无线网络安装Ubuntu Server启动系统后连接无线网络的方法
- 在Ubuntu上搭建网桥的方法
- ubuntu 虚拟机上网方式及相关配置详解
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.
这篇CFSDN的博客文章基于spring实现websocket实时推送实例由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.
基于spring框架来写的,websocket实时推送例子,具体内容如下 。
第一步:自己搭建一个springmvc项目,很简单,网上百度都有;pom文件添加以下:
1
|
2
3
4
5
6
7
8
9
10
11
12
13
|
<!-- WebSocket -->
<
dependency
>
<
groupId
>org.springframework</
groupId
>
<
artifactId
>spring-websocket</
artifactId
>
<
version
>4.2.4.RELEASE</
version
>
</
dependency
>
<
dependency
>
<
groupId
>org.springframework</
groupId
>
<
artifactId
>spring-messaging</
artifactId
>
<
version
>4.2.4.RELEASE</
version
>
</
dependency
>
|
我的spring版本是4.2.4的,所以websocket也是4.2.4的;websocket最好和spring版本保持一致 。
第二步:编写消息处理器 。
1
|
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
|
/**
* Project Name:springRabbitMQ
* File Name:MyMessageHandler.java
* Package Name:com.zsy.websocket
* Date:2018年1月31日上午11:10:03
* Copyright (c) 2018, zhaoshouyun All Rights Reserved.
*
*/
package
com.zsy.websocket;
import
java.io.IOException;
import
java.util.Map;
import
java.util.Set;
import
java.util.concurrent.ConcurrentHashMap;
import
org.apache.commons.lang3.StringUtils;
import
org.springframework.web.socket.CloseStatus;
import
org.springframework.web.socket.TextMessage;
import
org.springframework.web.socket.WebSocketHandler;
import
org.springframework.web.socket.WebSocketMessage;
import
org.springframework.web.socket.WebSocketSession;
/**
* ClassName: MyMessageHandler
* Function: 实现webscoket接口
* date: 2018年1月31日 上午11:10:03
* @author zhaoshouyun
* @version
* @since JDK 1.7
*/
public
class
MyMessageHandler
implements
WebSocketHandler {
//用户key
public
static
final
String USER_KEY =
"current_user"
;
/**
* userMap:存储用户连接webscoket信息
* @since JDK 1.7
*/
private
final
static
Map<String, WebSocketSession> userMap;
static
{
userMap =
new
ConcurrentHashMap<String,WebSocketSession>(
30
);
}
/**
* 关闭websocket时调用该方法
* @see org.springframework.web.socket.WebSocketHandler#afterConnectionClosed(org.springframework.web.socket.WebSocketSession, org.springframework.web.socket.CloseStatus)
*/
@Override
public
void
afterConnectionClosed(WebSocketSession session, CloseStatus status)
throws
Exception {
String userId =
this
.getUserId(session);
if
(StringUtils.isNoneBlank(userId)){
userMap.remove(userId);
System.err.println(
"该"
+ userId +
"用户已成功关闭"
);
}
else
{
System.err.println(
"关闭时,获取用户id为空"
);
}
}
/**
* 建立websocket连接时调用该方法
* @see org.springframework.web.socket.WebSocketHandler#afterConnectionEstablished(org.springframework.web.socket.WebSocketSession)
*/
@Override
public
void
afterConnectionEstablished(WebSocketSession session)
throws
Exception {
String userId =
this
.getUserId(session);
if
(StringUtils.isNoneBlank(userId)){
userMap.put(userId, session);
session.sendMessage(
new
TextMessage(
"建立WebSocket连接成功!"
));
}
}
/**
* 客户端调用websocket.send时候,会调用该方法,进行数据通信
* @see org.springframework.web.socket.WebSocketHandler#handleMessage(org.springframework.web.socket.WebSocketSession, org.springframework.web.socket.WebSocketMessage)
*/
@Override
public
void
handleMessage(WebSocketSession session, WebSocketMessage<?> message)
throws
Exception {
String msg = message.toString();
String userId =
this
.getUserId(session);
System.err.println(
"该"
+userId+
"用户发送的消息是:"
+msg);
message =
new
TextMessage(
"服务端已经接收到消息,msg="
+msg);
session.sendMessage(message);
}
/**
* 传输过程出现异常时,调用该方法
* @see org.springframework.web.socket.WebSocketHandler#handleTransportError(org.springframework.web.socket.WebSocketSession, java.lang.Throwable)
*/
@Override
public
void
handleTransportError(WebSocketSession session, Throwable e)
throws
Exception {
WebSocketMessage<String> message =
new
TextMessage(
"异常信息:"
+e.getMessage());
session.sendMessage(message);
}
/**
*
* @see org.springframework.web.socket.WebSocketHandler#supportsPartialMessages()
*/
@Override
public
boolean
supportsPartialMessages() {
return
false
;
}
/**
* sendMessageToUser:发给指定用户
* @author zhaoshouyun
* @param userId
* @param contents
* @since JDK 1.7
*/
public
void
sendMessageToUser(String userId,String contents) {
WebSocketSession session = userMap.get(userId);
if
(session !=
null
&& session.isOpen()) {
try
{
TextMessage message =
new
TextMessage(contents);
session.sendMessage(message);
}
catch
(IOException e) {
e.printStackTrace();
}
}
}
/**
* sendMessageToAllUsers:发给所有的用户
* @author zhaoshouyun
* @param contents
* @since JDK 1.7
*/
public
void
sendMessageToAllUsers(String contents) {
Set<String> userIds = userMap.keySet();
for
(String userId: userIds) {
this
.sendMessageToUser(userId, contents);
}
}
/**
* getUserId:获取用户id
* @author zhaoshouyun
* @param session
* @return
* @since JDK 1.7
*/
private
String getUserId(WebSocketSession session){
try
{
String userId = (String)session.getAttributes().get(USER_KEY);
return
userId;
}
catch
(Exception e) {
e.printStackTrace();
}
return
null
;
}
}
|
第三步:编写websocket相关配置,当然可以在xml配置;我现在没有使用xml配置,使用代码配置,需要在xml里添加扫描包<context:component-scan base-package="com.zsy.websocket" /> 。
。
1
|
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
/**
* Project Name:springRabbitMQ
* File Name:WebSocketConfig.java
* Package Name:com.zsy.websocket
* Date:2018年1月31日下午1:10:33
* Copyright (c) 2018, zhaoshouyun All Rights Reserved.
*
*/
/**
* Project Name:springRabbitMQ
* File Name:WebSocketConfig.java
* Package Name:com.zsy.websocket
* Date:2018年1月31日下午1:10:33
* Copyright (c) 2018, zhaoshouyun All Rights Reserved.
*
*/
package
com.zsy.websocket;
import
org.springframework.context.annotation.Bean;
import
org.springframework.context.annotation.Configuration;
import
org.springframework.web.socket.WebSocketHandler;
import
org.springframework.web.socket.config.annotation.EnableWebSocket;
import
org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import
org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
/**
* ClassName: WebSocketConfig
* Function: TODO ADD FUNCTION.
* date: 2018年1月31日 下午1:10:33
* @author zhaoshouyun
* @version
* @since JDK 1.7
*/
@Configuration
@EnableWebSocket
public
class
WebSocketConfig
implements
WebSocketConfigurer {
/**
* 注册handle
* @see org.springframework.web.socket.config.annotation.WebSocketConfigurer#registerWebSocketHandlers(org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry)
*/
@Override
public
void
registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(),
"/testHandler"
).addInterceptors(
new
WebSocketInterceptor());
registry.addHandler(myHandler(),
"/socketJs/testHandler"
).addInterceptors(
new
WebSocketInterceptor()).withSockJS();
}
@Bean
public
WebSocketHandler myHandler(){
return
new
MyMessageHandler();
}
}
|
1
|
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
package
com.zsy.websocket;
import
java.util.Map;
import
org.springframework.http.server.ServerHttpRequest;
import
org.springframework.http.server.ServerHttpResponse;
import
org.springframework.http.server.ServletServerHttpRequest;
import
org.springframework.web.socket.WebSocketHandler;
import
org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
/**
* ClassName: WebSocketInterceptor
* Function: TODO ADD FUNCTION.
* date: 2018年1月31日 上午11:42:34
* @author zhaoshouyun
* @version
* @since JDK 1.7
*/
public
class
WebSocketInterceptor
extends
HttpSessionHandshakeInterceptor {
/**
* TODO 简单描述该方法的实现功能(可选).
* @see org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor#beforeHandshake(org.springframework.http.server.ServerHttpRequest, org.springframework.http.server.ServerHttpResponse, org.springframework.web.socket.WebSocketHandler, java.util.Map)
*/
@Override
public
boolean
beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes)
throws
Exception {
if
(request
instanceof
ServletServerHttpRequest){
ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest)request;
//获取参数
String userId = serverHttpRequest .getServletRequest().getParameter(
"userId"
);
attributes.put(MyMessageHandler.USER_KEY, userId);
}
return
true
;
}
}
|
第五步对应的js:
1
|
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
http://www.w3.org/TR/html4/loose.dtd
">
<
html
>
<
head
>
<
meta
http-equiv
=
"Content-Type"
content
=
"text/html; charset=ISO-8859-1"
>
<
title
>Insert title here</
title
>
<
script
type
=
"text/javascript"
>
var websocket;
// 首先判断是否 支持 WebSocket
if('WebSocket' in window) {
websocket = new WebSocket("
ws://localhost:8085/springTest/testHandler?userId=zhaoshouyun
");
} else if('MozWebSocket' in window) {
websocket = new MozWebSocket("
ws://localhost:8085/springTest/testHandler?userId=zhaoshouyun
");
} else {
websocket = new SockJS("
http://localhost:8085/springTest/socketJs/testHandler?userId=zhaoshouyun
");
}
// 打开连接时
websocket.onopen = function(evnt) {
console.log(" websocket.onopen ");
};
// 收到消息时
websocket.onmessage = function(evnt) {
alert(evnt.data);
};
websocket.onerror = function(evnt) {
console.log(" websocket.onerror ");
};
websocket.onclose = function(evnt) {
console.log(" websocket.onclose ");
};
function say(){
//客户端主动发消息
websocket.send(document.getElementById('msg').value);
}
</
script
>
</
head
>
<
body
>
<
input
type
=
"text"
value
=
""
id
=
"msg"
><
button
onclick
=
"say()"
></
button
>
</
body
>
</
html
>
|
第六步测试:
1
|
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
package
com.zsy.test.controller;
import
java.util.HashMap;
import
java.util.Map;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.beans.factory.annotation.Value;
import
org.springframework.stereotype.Controller;
import
org.springframework.web.bind.annotation.RequestBody;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.ResponseBody;
import
com.zsy.websocket.MyMessageHandler;
/**
* ClassName: TestController
* Function: TODO ADD FUNCTION.
* date: 2017年12月14日 上午11:11:23
* @author zhaoshouyun
* @version
* @since JDK 1.7
*/
@Controller
public
class
TestController {
@Autowired
MyMessageHandler handler;
@RequestMapping
(
"/get"
)
public
String get(){
return
"index"
;
}
@ResponseBody
@RequestMapping
(
"/get1"
)
public
String send(String name){
handler.sendMessageToUser(
"zhaoshouyun"
,
"服务端发送的内容:"
+name);
return
"success"
;
}
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我.
原文链接:https://blog.csdn.net/u011410254/article/details/79216642 。
最后此篇关于基于spring实现websocket实时推送实例的文章就讲到这里了,如果你想了解更多关于基于spring实现websocket实时推送实例的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
假设浏览器被强制终止,并且没有关闭消息发送到 Tornado 服务器。 Tornado 怎么知道(或者它甚至知道?)这个连接已经在客户端终止了?翻看Tornado websocket code这对我来
我目前正在开发一款使用 WebSockets 的基于浏览器的多人游戏。我的首要任务是低延迟以及与各种平台和网络设置的兼容性。 但是我正在做密码验证。我还有聊天功能,我认为玩家的隐私很重要。因此,我认为
我必须设计一个解决方案,允许通过远程托管的网络应用程序读取本地传感器生成的实时数据。 设计仍在进行中:传感器的数据可以由安装在客户端计算机上的 Windows 应用程序/服务处理,或者由位于客户端计算
WebSocket的端口是什么? WebSocket 使用什么协议(protocol)? 当防火墙阻止除 80 和 443 端口之外的所有端口时,WebSocket 是否工作? 最佳答案 What i
有一个 fantastic answer其中详细介绍了 REST apis 的工作原理。 websockets 如何以类似的细节工作? 最佳答案 Websocket 创建并代表了服务器和客户端之间双向
请原谅我的无知,因为我在负载均衡器和 websockets 方面的经验有限。我试图了解客户端如何通过 websockets 连接到位于负载均衡器后面的服务器集群。 我对负载均衡器的理解是它们就像反向代
我正在尝试使用 websocket 发送音频消息,我应该将音频流更改为什么类型的消息,以便我可以使用套接字发送? 如果我直接使用 websocket.send(audio),我会得到一个错误“DOME
我对 WebSockets 的前景感到非常兴奋。由于我在过去构建了一些基于桌面套接字的游戏和 Web 游戏,因此我热衷于将这两种方法结合起来构建基于 Web 的多人游戏,而无需长时间轮询。 自从 Fi
我读过很多关于实时推送通知的文章。并且简历是 websocket 通常是首选技术,只要您不关心 100% 的浏览器兼容性。然而,one article指出 Long polling - potenti
我很难找到文档或教程,以便通过网络套接字发送文件。 这是我的JS: ['dragleave', 'drop'].forEach(event_name => document.addEventListe
我正在使用 Dart 的 WebSocket 类(dart:io 和 dart:html 版本)连接到 Dart WebSocket 服务器。当我让客户端使用自定义关闭代码和原因关闭 Web 套接字连
谷歌浏览器框架是否支持 websocket? 最佳答案 答案是肯定的,Chrome Frame supports websockets .我不确定,但这也可能取决于您安装的 Chrome 版本。我有
是否可以在同一应用程序(同一端口)中托管一个普通 Bottle 应用程序和一个 WebSocket 应用程序(例如: https://github.com/defnull/bottle/blob/ma
我有一个支持网络套接字的服务器。浏览器连接到我的网站,每个浏览器都会打开一个到 www.mydomain.example 的 Web 套接字。这样,我的社交网络应用程序就可以向客户端推送消息。 传统上
我是 Websockets 新手。在阅读有关 websockets 的内容时,我无法找到一些疑问的答案。我希望有人能澄清一下。 websocket 是否仅将数据广播到所有连接的客户端而不是发送到特定客
客户端可以通过 websockets 连接到服务器多长时间?是否有时间限制,它们是否有可能连在一起多年? 最佳答案 理论上,WebSocket 连接可以永远持续下去。假设端点保持正常运行,长期存在的
我正在尝试使用 websockets 制作自己的聊天客户端,并认为我会从 Tomcat 7 websocket chat example code. 开始。 .我已经成功编译并部署了ChatAnnot
我有一个使用 AdSense 的应用程序,据我所知,由于 AdSense 政策,不允许进行轮询。我想知道如果我使用 WebSockets 并且服务器在创建新数据时向客户端发送新数据并且在客户端上显示新
在 servlet 世界中,我会使用 cookie 和 HttpSession 之类的东西来识别谁在访问我的 Restful 服务以将请求路由到正确的数据。将 Sec-WebSocket-Key 用作
我必须使用 websocket 实现一个聊天应用程序,用户将通过群组聊天,可以有数千个群组,并且一个用户可以在多个群组中。我正在考虑两种解决方案: [1] 对于每个群聊,我创建一个 websocket
我是一名优秀的程序员,十分优秀!