Java整合WebSocket实现实时推送(注解版)
第⼀次写博客,备份下代码,顺便给需要的同学看看,
⽹上也有很多Java整合webSocket的例⼦,⼤多⾃⼰写个类继承WebSocketConfigurer ,
直接使⽤注解的⽐较少,我也看了很多写的运⾏有问题,要么代码关键部分缺少,想着⾃⼰弄⼀个好了,这个版本在⽹上某些⼤佬的基础上实现的,基础代码重复写没意义。
1.加⼊websocket依赖包
<!-- WebSocket -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>${spring.version}</version>
</dependency>
2.在Namespaces中勾选websocket
3.配置请求地址
<!-- 配置webSockte -->
<!-- 实现webscoket接⼝ -->
<bean id="wsHandler" class="com.spd.sw.websocket.MyMessageHandler"/>
<websocket:handlers allowed-origins="*">
<!-- 前端握⼿请求地址 -->
<websocket:mapping path="/socketServer" handler="wsHandler"/>
<websocket:handshake-interceptors>
<bean class="com.spd.sw.websocket.WebSocketInterceptor"/>
</websocket:handshake-interceptors>
</websocket:handlers>
4.配置
public class WebSocketInterceptor extends HttpSessionHandshakeInterceptor {
/**
* TODO 描述该⽅法的实现功能.
* @see org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor#beforeHandshake(org.springframework.http.server.ServerHttpReq */
@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;
}
}
5.socket⽤户及msg
/**
* ClassName: MyMessageHandler
* Function: 实现webscoket接⼝
* @version
*/
@Service
public class MyMessageHandler implements WebSocketHandler {
//⽤户
public static final String USER_KEY = "socket_user";
/**
* userMap:存储⽤户连接webscoket信息
* @since JDK 1.7
*/
private final static int size=300;//⽤户数量
private final static Map<String, WebSocketSession> userMap;
static {
userMap = new ConcurrentHashMap<String,WebSocketSession>(size);
}
/**
* 关闭websocket时调⽤该⽅法
* @see org.springframework.web.socket.WebSocketHandler#afterConnectionClosed(org.springframework.web.socket.WebSocketSession, org.springframewo */
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception
{
String userId = UserId(session);
if(StringUtils.isNoneBlank(userId)){
}else{
}
}
/**
* 建⽴websocket连接时调⽤该⽅法
* @see org.springframework.web.socket.WebSocketHandler#afterConnectionEstablished(org.springframework.web.socket.WebSocketSession)
*/
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
String userId = UserId(session);
String userId = UserId(session);
if(StringUtils.isNoneBlank(userId)){
userMap.put(userId, session);
//session.sendMessage(new TextMessage("⽤户"+userId+"建⽴WebSocket连接成功!")); //给所有⽤户发送消息
}
}
/**
* 客户端调⽤websocket.send时候,会调⽤该⽅法,进⾏数据通信
* @see org.springframework.web.socket.WebSocketHandler#handleMessage(org.springframework.web.socket.WebSocketSession, org.springframework.web */
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
String msg = String();
String userId = UserId(session);
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:发给指定⽤户
*
* @param userId
* @param contents
* @since JDK 1.7
*/
public void sendMessageToUser(String userId,String contents) {
WebSocketSession session = (userId);
if(session !=null && session.isOpen()) {
try {
TextMessage message = new TextMessage(contents);
session.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* sendMessageToAllUsers:发给所有的⽤户
*
* @param contents
* @since JDK 1.7
* @since JDK 1.7
*/
public void sendMessageToAllUsers(String contents) {
Set<String> userIds = userMap.keySet();
for(String userId: userIds) {
this.sendMessageToUser(userId, contents);
}
}
/**
* getUserId:获取⽤户id
*
*
* @param session
* @return
* @since JDK 1.7
*/
private String getUserId(WebSocketSession session){
try {
String userId = (Attributes().get(USER_KEY);
return userId;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
6.在springmvc controller中加⼊
@RequestMapping("/socket")
@Controller
public class WebSocketController {
@Autowired
MyMessageHandler myMessageHandler;
/**
* 对单个⽤户推送消息
* @return
* @throws ParseException
*/
@RequestMapping("/sendMessageByUser")
@ResponseBody
public String sendMessageByUser(@RequestParam Map<String, Object> contents) throws ParseException{ task();
websocket和socketreturn "success";
}
/**
* 对所有⽤户推送消息
* @return
*/
@RequestMapping("/sendMessageByAll")
@ResponseBody
public String sendMessageByAll(@RequestParam Map<String, Object> contents){
myMessageHandler.("msg").toString());
return "success";
}
}
7.前端js
$(document).ready(function () {
window.websocket={};
var userId='webPower';
var api='你的IP';
var app={
/**
*初始化socket,判断是否⽀持webSocket
*/
initSocket:function () {
if('WebSocket' in window) {
websocket = new WebSocket("ws://"+api+"/socketServer?userId="+userId);
} else if('MozWebSocket' in window) {
websocket = new MozWebSocket("ws://"+api+"/socketServer?userId="+userId); } else {
websocket = new SockJS(""+api+"/sockjs/socketServer?userId="+userId); }
app.state();
},
/**
* 状态
*/
state:function () {
// 打开连接时
console.log("websocket已启⽤");
};
// 收到消息时
};
//出错时
console.log("与后台握⼿出现问题!");
};
//关闭时
console.log("正在关闭 webSocket ");
};
//发送消息
/
/ websocket.send(msg);
}
};
app.initSocket();
});
8.效果
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论