码迷,mamicode.com
首页 > 编程语言 > 详细

WebSocket-java实践

时间:2018-11-08 22:01:10      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:gen   vax   lse   messages   server   string   sop   owa   http   

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实践

标签:gen   vax   lse   messages   server   string   sop   owa   http   

原文地址:https://www.cnblogs.com/loadL/p/webSocket.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!