WebSocket-java实践
Posted loadl
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WebSocket-java实践相关的知识,希望对你有一定的参考价值。
websocket 主要用于 前端页面hmtl/jsp 与 后端进行socket得连接。
本例简单实现:一但后端接收到数据或者根据某些规则主动发送数据,那么可以根据不同用户等区别,发送给某个登陆得页面上。
WebSocketConfig 类
package
import javax.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
@Resource
Jim_Handler handler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(handler, "/websocket.do").setAllowedOrigins("*").addInterceptors(new JimHandShake());
registry.addHandler(handler, "/websocket/sockjs.do").addInterceptors(new JimHandShake()).withSockJS();
}
}
Jim_Handler 类
@Component
public classJim_Handler implements WebSocketHandler{
public static final List<WebSocketSession> sessionList;
static{
sessionList = new ArrayList<WebSocketSession>();
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus arg1)
throws Exception {
boolean flag = false;
for (int i=0;i<sessionList.size();i++) {
if(session.getId().equals(sessionList.get(i).getId())){
flag = true;
break;
}
}
if(flag){
sessionList.remove(session);
}
}
@Override
public void afterConnectionEstablished(WebSocketSession session)
throws Exception {
sessionList.add(session);
}
@Override
public void handleMessage(WebSocketSession arg0, WebSocketMessage<?> arg1)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void handleTransportError(WebSocketSession arg0, Throwable arg1)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public boolean supportsPartialMessages() {
// TODO Auto-generated method stub
return false;
}
public void sendMessageToAllClients(final TextMessage message) throws IOException{
for (int i = 0; i < sessionList.size(); i++) {
WebSocketSession session = sessionList.get(i);
if (session.isOpen()) {
session.sendMessage(message);
}
}
}
}
JimHandShake 类
import java.util.Map;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
public class JimHandShake implements HandshakeInterceptor{
@Override
public void afterHandshake(ServerHttpRequest arg0, ServerHttpResponse arg1,
WebSocketHandler arg2, Exception arg3) {
}
@Override
public boolean beforeHandshake(ServerHttpRequest request,
ServerHttpResponse arg1, WebSocketHandler arg2,
Map<String, Object> attributes) throws Exception {
return true;
}
}
发送消息(任何类)
@Resource
private JimHandler jHandler;
S s = new S("1","2");
TextMessage textMessage = new TextMessage(JSON.toJSONString(s));
jHandler.sendMessageToAllClients(textMessage);
前端发送请求
//websocket初始化
var websocket;
var path = ‘<%=basePath_websocket%>‘; //10.0.1.1:8080
if (‘WebSocket‘ in window) {
websocket = new WebSocket("ws://" + path + "/websocket/.do");
} else if (‘MozWebSocket‘ in window) {
websocket = new MozWebSocket("ws://" + path + "/websocket.do");
} else {
websocket = new SockJS("http://" + path + "/socket/sockjs.do");
}
//websocket 连接
websocket.onopen = function(event) {
console.log("WebSocket:已连接");
};
//websocket通信时
websocket.onmessage = function(event) {
event.data
}
//socket连接出错
websocket.onerror = function(event) {
layer.msg(‘socket连接出错‘);
};
//断开socket连接
websocket.onclose = function(event) {
layer.msg(‘socket连接断开‘);
};
以上是关于WebSocket-java实践的主要内容,如果未能解决你的问题,请参考以下文章
[Java 并发] Java并发编程实践 思维导图 - 第一章 简单介绍
JAVA爬虫实践(实践三:爬虫框架webMagic和csdnBlog爬虫)