美文网首页
Java实现websocket 的两种方法(实例介绍)

Java实现websocket 的两种方法(实例介绍)

作者: 微笑吧_5464 | 来源:发表于2018-10-18 09:51 被阅读0次

1.Tomcat实现websocket方法

1.1 新建JavaWeb测试项目

image.png

1.2 在pom.xml中添加Jar包依赖

 <dependency>
         <groupId>javax</groupId>
         <artifactId>javaee-api</artifactId>
         <version>7.0</version>
         <scope>provided</scope>
 </dependency>

2. Spring整合websocket方法(基于Spring MVC 框架)

2.1 WebSocketConfig.java

  • 这个类是配置类,所以需要在spring mvc配置文件中加入对这个类的扫描,第一个addHandler是对正常连接的配置,第二个是如果浏览器不支持websocket,使用socketjs模拟websocket的连接。
package com.websocket;  
  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.web.socket.config.annotation.EnableWebSocket;  
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;  
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;  
import org.springframework.web.socket.handler.TextWebSocketHandler;  
  
@Configuration  
@EnableWebSocket  
public class WebSocketConfig implements WebSocketConfigurer {  
    @Override  
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {  
        registry.addHandler(chatMessageHandler(),"/webSocketServer").addInterceptors(new ChatHandshakeInterceptor());  
        registry.addHandler(chatMessageHandler(), "/sockjs/webSocketServer").addInterceptors(new ChatHandshakeInterceptor()).withSockJS();  
    }  
   
    @Bean  
    public TextWebSocketHandler chatMessageHandler(){  
        return new ChatMessageHandler();  
    }  
}  

2.2 ChatHandshakeInterceptor.java

  • 这个类的作用就是在连接成功前和成功后增加一些额外的功能,Constants.java类是一个工具类,两个常量。
package com.websocket;  
  
import java.util.Map;  
import org.apache.shiro.SecurityUtils;  
import org.springframework.http.server.ServerHttpRequest;  
import org.springframework.http.server.ServerHttpResponse;  
import org.springframework.web.socket.WebSocketHandler;  
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;  
  
public class ChatHandshakeInterceptor extends HttpSessionHandshakeInterceptor {  
  
    @Override  
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,  
            Map<String, Object> attributes) throws Exception {  
        System.out.println("Before Handshake");  
        /* 
         * if (request instanceof ServletServerHttpRequest) { 
         * ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) 
         * request; HttpSession session = 
         * servletRequest.getServletRequest().getSession(false); if (session != 
         * null) { //使用userName区分WebSocketHandler,以便定向发送消息 String userName = 
         * (String) session.getAttribute(Constants.SESSION_USERNAME); if 
         * (userName==null) { userName="default-system"; } 
         * attributes.put(Constants.WEBSOCKET_USERNAME,userName); 
         *  
         * } } 
         */  
  
        //使用userName区分WebSocketHandler,以便定向发送消息(使用shiro获取session,或是使用上面的方式)  
        String userName = (String) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION_USERNAME);  
        if (userName == null) {  
            userName = "default-system";  
        }  
        attributes.put(Constants.WEBSOCKET_USERNAME, userName);  
  
        return super.beforeHandshake(request, response, wsHandler, attributes);  
    }  
  
    @Override  
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,  
            Exception ex) {  
        System.out.println("After Handshake");  
        super.afterHandshake(request, response, wsHandler, ex);  
    }  
}  

2.3 ChatMessageHandler.java

  • 这个类是对消息的一些处理,比如是发给一个人,还是发给所有人,并且前端连接时触发的一些动作.
package com.websocket;  
  
import java.io.IOException;  
import java.util.ArrayList;  
import org.apache.log4j.Logger;  
import org.springframework.web.socket.CloseStatus;  
import org.springframework.web.socket.TextMessage;  
import org.springframework.web.socket.WebSocketSession;  
import org.springframework.web.socket.handler.TextWebSocketHandler;  
  
public class ChatMessageHandler extends TextWebSocketHandler {  
  
    private static final ArrayList<WebSocketSession> users;// 这个会出现性能问题,最好用Map来存储,key用userid  
    private static Logger logger = Logger.getLogger(ChatMessageHandler.class);  
  
    static {  
        users = new ArrayList<WebSocketSession>();  
    }  
  
    /** 
     * 连接成功时候,会触发UI上onopen方法 
     */  
    @Override  
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {  
        System.out.println("connect to the websocket success......");  
        users.add(session);  
        // 这块会实现自己业务,比如,当用户登录后,会把离线消息推送给用户  
        // TextMessage returnMessage = new TextMessage("你将收到的离线");  
        // session.sendMessage(returnMessage);  
    }  
  
    /** 
     * 在UI在用js调用websocket.send()时候,会调用该方法 
     */  
    @Override  
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {  
        sendMessageToUsers(message);  
        //super.handleTextMessage(session, message);  
    }  
  
    /** 
     * 给某个用户发送消息 
     * 
     * @param userName 
     * @param message 
     */  
    public void sendMessageToUser(String userName, TextMessage message) {  
        for (WebSocketSession user : users) {  
            if (user.getAttributes().get(Constants.WEBSOCKET_USERNAME).equals(userName)) {  
                try {  
                    if (user.isOpen()) {  
                        user.sendMessage(message);  
                    }  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
                break;  
            }  
        }  
    }  
  
    /** 
     * 给所有在线用户发送消息 
     * 
     * @param message 
     */  
    public void sendMessageToUsers(TextMessage message) {  
        for (WebSocketSession user : users) {  
            try {  
                if (user.isOpen()) {  
                    user.sendMessage(message);  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
  
    @Override  
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {  
        if (session.isOpen()) {  
            session.close();  
        }  
        logger.debug("websocket connection closed......");  
        users.remove(session);  
    }  
  
    @Override  
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {  
        logger.debug("websocket connection closed......");  
        users.remove(session);  
    }  

    @Override  
    public boolean supportsPartialMessages() {  
        return false;  
    }  
}  

2.4 spring-mvc.xml

  • 正常的配置文件,同时需要增加对WebSocketConfig.java类的扫描,并且增加
xmlns:websocket="http://www.springframework.org/schema/websocket"  
              http://www.springframework.org/schema/websocket   
              <a target="_blank" href="http://www.springframework.org/schema/websocket/spring-websocket-4.1.xsd">http://www.springframework.org/schema/websocket/spring-websocket-4.1.xsd</a>  

2.5 客户端

<script type="text/javascript"  
        src="http://localhost:8080/Bank/js/sockjs-0.3.min.js"></script>  
    <script>  
        var websocket;  
      
        if ('WebSocket' in window) {  
            websocket = new WebSocket("ws://" + document.location.host + "/Bank/webSocketServer");  
        } else if ('MozWebSocket' in window) {  
            websocket = new MozWebSocket("ws://" + document.location.host + "/Bank/webSocketServer");  
        } else {  
            websocket = new SockJS("http://" + document.location.host + "/Bank/sockjs/webSocketServer");  
        }  
      
        websocket.onopen = function(evnt) {};  
        websocket.onmessage = function(evnt) {  
            $("#test").html("(<font color='red'>" + evnt.data + "</font>)")  
        };  
      
        websocket.onerror = function(evnt) {};  
        websocket.onclose = function(evnt) {}  
      
        $('#btn').on('click', function() {  
            if (websocket.readyState == websocket.OPEN) {  
                var msg = $('#id').val();  
                //调用后台handleTextMessage方法  
                websocket.send(msg);  
            } else {  
                alert("连接失败!");  
            }  
        });  
    </script>  

相关文章

网友评论

      本文标题:Java实现websocket 的两种方法(实例介绍)

      本文链接:https://www.haomeiwen.com/subject/uqkjzftx.html