zoukankan      html  css  js  c++  java
  • 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连接断开');

    };

          

  • 相关阅读:
    利用 Remoting 实现异步队列机制
    JsonHelper
    吐血推荐"泛绿色编程工具": EditPlus 已于 20100714 升级到 v3.12(602)
    以 Console 方式运行、调试、编译 .Net 编写的 Windows 服务
    CompressHelper
    支持掩码输入的 .Net 2.0 Console 可用于使用掩码回显 password 的字符
    20080411 正式版 Microsoft Visual Studio International Pack 1.0 处理汉字、拼音、笔画转换
    CryptoHelper
    C++之String的find方法,查找一个字符串在另一个字符串的什么位置;leveldb字符串转数字解析办法
    Linux线程之线程池、高并发、线程数 C/C++ pthread 函数库
  • 原文地址:https://www.cnblogs.com/loadL/p/webSocket.html
Copyright © 2011-2022 走看看