我去!你竟然不知道Spring MVC中有现成的WebSocket组件...
Posted Java面试那些事儿
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我去!你竟然不知道Spring MVC中有现成的WebSocket组件...相关的知识,希望对你有一定的参考价值。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
@Configuration
@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer{
private static final Logger logger = LoggerFactory.getLogger(WebSocketConfig.class);
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
System.out.println("==========================注册socket");
//注册websocket server实现类,"/webSocketServer"访问websocket的地址
registry.addHandler(msgSocketHandle(),
"/webSocketServer").
addInterceptors(new WebSocketHandshakeInterceptor());
//使用socketjs的注册方法
registry.addHandler(msgSocketHandle(),
"/sockjs/webSocketServer").
addInterceptors(new WebSocketHandshakeInterceptor())
.withSockJS();
}
/**
*
* @return 消息发送的Bean
*/
"msgSocketHandle") (name =
public WebSocketHandler msgSocketHandle(){
return new MsgScoketHandle();
}
}
<mvc:annotation-driven />
<context:component-scan base-package="com.wqh.websocket"/>
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {
private static final Logger logger = LoggerFactory.getLogger(WebSocketHandshakeInterceptor.class);
/**
* 握手前
* @param request
* @param response
* @param webSocketHandler
* @param attributes
* @return
* @throws Exception
*/
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler, Map<String, Object> attributes) throws Exception {
logger.info("握手操作");
if (request instanceof ServletServerHttpRequest){
ServletServerHttpRequest servletServerHttpRequest = (ServletServerHttpRequest) request;
HttpSession session = servletServerHttpRequest.getServletRequest().getSession(false);
if(session != null){
//从session中获取当前用户
User user = (User) session.getAttribute("user");
attributes.put("user",user);
}
}
return true;
}
/**
* 握手后
* @param serverHttpRequest
* @param serverHttpResponse
* @param webSocketHandler
* @param e
*/
public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
}
}
@Component
public class MsgScoketHandle implements WebSocketHandler {
/**已经连接的用户*/
private static final ArrayList<WebSocketSession> users;
static {
//保存当前连接用户
users = Lists.newArrayList();
}
/**
* 建立链接
* @param webSocketSession
* @throws Exception
*/
public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
//将用户信息添加到list中
users.add(webSocketSession);
System.out.println("=====================建立连接成功==========================");
User user = (User) webSocketSession.getAttributes().get("user");
if(user != null){
System.out.println("当前连接用户======"+user.getName());
}
System.out.println("webSocket连接数量====="+users.size());
}
/**
* 接收消息
* @param webSocketSession
* @param webSocketMessage
* @throws Exception
*/
public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
User user = (User) webSocketSession.getAttributes().get("user");
System.out.println("收到用户:"+user.getName()+"的消息");
System.out.println(webSocketMessage.getPayload().toString());
System.out.println("===========================================");
}
/**
* 异常处理
* @param webSocketSession
* @param throwable
* @throws Exception
*/
public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable){
if (webSocketSession.isOpen()){
//关闭session
try {
webSocketSession.close();
} catch (IOException e) {
}
}
//移除用户
users.remove(webSocketSession);
}
/**
* 断开链接
* @param webSocketSession
* @param closeStatus
* @throws Exception
*/
public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
users.remove(webSocketSession);
User user = (User) webSocketSession.getAttributes().get("user");
System.out.println(user.getName()+"断开连接");
}
public boolean supportsPartialMessages() {
return false;
}
/**
* 发送消息给指定的用户
* @param user
* @param messageInfo
*/
public void sendMessageToUser(User user, TextMessage messageInfo){
for (WebSocketSession session : users) {
User sessionUser = (User) session.getAttributes().get("user");
//根据用户名去判断用户接收消息的用户
if(user.getName().equals(sessionUser.getName())){
try {
if (session.isOpen()){
session.sendMessage(messageInfo);
System.out.println("发送消息给:"+user.getName()+"内容:"+messageInfo);
}
break;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
这里简单的模拟登录,前台传入登录参数,直接将参数保存到session中。
"websocket") (
@Controller
public class UserController {
private MsgScoketHandle msgScoketHandle;
"login") (
public String login(User user, HttpServletRequest request){
user.setId(UUID.randomUUID().toString().replace("-",""));
request.getSession().setAttribute("user",user);
return "/index";
}
"sendMsg") (
public String sendMag(String content,String toUserName){
User user = new User();
user.setName(toUserName);
TextMessage textMessage = new TextMessage(content);
msgScoketHandle.sendMessageToUser(user,textMessage);
return "200";
}
}
<script>
$(document).ready(function() {
var ws;
if ('WebSocket' in window) {
ws = new WebSocket("ws://"+window.location.host+"/webSocketServer");
} else if ('MozWebSocket' in window) {
ws = new MozWebSocket("ws://"+window.location.host+"/webSocketServer");
} else {
//如果是低版本的浏览器,则用SockJS这个对象,对应了后台“sockjs/webSocketServer”这个注册器,
//它就是用来兼容低版本浏览器的
ws = new SockJS("http://"+window.location.host+"/sockjs/webSocketServer");
}
ws.onopen = function (evnt) {
};
//接收到消息
ws.onmessage = function (evnt) {
alert(evnt.data);
$("#msg").html(evnt.data);
};
ws.onerror = function (evnt) {
console.log(evnt)
};
ws.onclose = function (evnt) {
}
$("#btn1").click(function () {
ws.send($("#text").val());
});
$("#btn2").bind("click",function () {
var url = "${pageContext.request.contextPath}/websocket/sendMsg";
var content = $("#text").val();
var toUserName = "admin"
$.ajax({
data: "content=" + content + "&toUserName=" + toUserName,
type: "get",
dataType: 'text',
async: false,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
encoding: "UTF-8",
url: url,
success: function (data) {
alert(data.toString());
},
error: function (msg) {
alert(msg);
},
});
})
});
</script>
<body>
当前登录用户:${pageContext.session.getAttribute("user").name}<br>
<input type="text" id="text">
<button id="btn1" value="发送给后台">发送给后台</button>
<button id="btn2" value="发送给其他用户">发送给其他用户</button>
<div id="msg"></div>
</body>
</html>
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/js/**" location="/js/" />
以上是关于我去!你竟然不知道Spring MVC中有现成的WebSocket组件...的主要内容,如果未能解决你的问题,请参考以下文章