spring整合websocket通信

2021-07-04 08:06

阅读:467

YPE html>

标签:example   参考   can   token   resources   inf   int   win   ble   

1. maven依赖

"1.0" encoding="UTF-8"?>

"http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4.0.0com.dxss.websocket
  WebSocketProGram
  1.0-SNAPSHOTwarWebSocketProGram Maven Webapphttp://www.example.comUTF-81.71.7com.fasterxml.jackson.core
      jackson-core
      2.3.0com.fasterxml.jackson.core
      jackson-databind
      2.3.0javax.servlet
      javax.servlet-api
      3.1.0providedorg.springframework
      spring-core
      4.2.4.RELEASEorg.springframework
      spring-beans
      4.2.4.RELEASEorg.springframework
      spring-tx
      4.2.4.RELEASEorg.springframework
      spring-context
      4.2.4.RELEASEorg.springframework
      spring-context-support
      4.2.4.RELEASEorg.springframework
      spring-web
      4.2.4.RELEASEorg.springframework
      spring-webmvc
      4.2.4.RELEASEorg.springframework
      spring-aop
      4.2.4.RELEASEcommons-lang
      commons-lang
      2.6providedorg.springframework
      spring-aspects
      4.2.4.RELEASEorg.springframework
      spring-jdbc
      4.2.4.RELEASEorg.springframework
      spring-orm
      4.2.4.RELEASEorg.springframework
      spring-webmvc
      4.2.4.RELEASEorg.springframework
      spring-websocket
      4.2.4.RELEASEorg.springframework
      spring-messaging
      4.2.4.RELEASEjunit
      junit
      4.11testcom.google.code.gson
          gson
          2.6.2WebSocketProGramorg.apache.tomcat.maven
          tomcat7-maven-plugin
          2.2/WebSocketProGram9092
          maven-clean-plugin
          3.0.0
          maven-resources-plugin
          3.0.2
          maven-compiler-plugin
          3.7.0
          maven-surefire-plugin
          2.20.1
          maven-war-plugin
          3.2.0
          maven-install-plugin
          2.5.2
          maven-deploy-plugin
          2.8.2

2. servletContext.xml

"1.0" encoding="UTF-8"?>
"http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:websocket="http://www.springframework.org/schema/websocket"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/websocket
       http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd">
    
    "websocket" class="com.web.common.util.websocket.MyWebSocketHander" />
    
    
"/visualizationWebSocket.do" handler="websocket" /> class="com.web.common.util.websocket.HandshakeInterceptor" />

3. servletContext-mvc.xml

"1.0" encoding="UTF-8"?>
"http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/task
       http://www.springframework.org/schema/task/spring-task.xsd">

    base-package="com.dxss.java.controller"/>
    default-servlet-handler/>
    "configProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        "locations">
            
                classpath:db.properties"fileEncoding" value="UTF-8">"ignoreUnresolvablePlaceholders" value="true">class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        "prefix" value="/WEB-INF/pages/"/>
        "suffix" value=".jsp"/>
    

4. webSocket配置

package com.web.common.util.websocket;

import org.springframework.context.annotation.Bean;
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.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 *  webSocket配置 : 注册websocket地址和处理类
 */
@Configuration
@EnableWebMvc
@EnableWebSocket
public class MyWebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // 这里的url要与页面的url一致
        // 前台 可以使用websocket环境
        registry.addHandler(myWebSocketHandler(),"/visualizationWebSocket.do").addInterceptors(new HandshakeInterceptor());
        //至于这里为什么要加info,我遇见的情况是,当我使用sockjs来代替websocket时,连接的后面会自动加上info
        //前台 不可以使用websocket环境,则使用sockjs进行模拟连接
        registry.addHandler(myWebSocketHandler(), "/sockjs/visualizationWebSocket/info").addInterceptors(new HandshakeInterceptor())
                .withSockJS();
    }

    /**
     * websocket 处理类
     *
     * @return
     */
    @Bean
    public WebSocketHandler myWebSocketHandler(){
        return new MyWebSocketHander();
    }



}

5. 会话拦截器

package com.web.common.util.websocket;

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;
import java.util.Map;

/**
 * 创建握手(handshake)接口/拦截器
 * desc : 这个的主要作用是可以在握手前做一些事,把所需要的东西放入到attributes里面,
 *        然后可以在WebSocketHandler的session中,取到相应的值,具体可参考HttpSessionHandshakeInterceptor,
 *        这儿也可以实现HandshakeInterceptor接口
 *
 * @author lenovo
 */
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {

    @Override
    public boolean beforeHandshake(
            ServerHttpRequest request,
            ServerHttpResponse response,
            WebSocketHandler wsHandler,
            Map attributes
    ) throws Exception {
        /**
         *   获取请求参数,首先我们要获取HttpServletRequest对象才能获取请求参数;
         *   当ServerHttpRequset的层次结构打开后其子类可以获取到我们想要的http对象,那么就简单了。
            我这里是把获取的请求数据绑定到session的map对象中(attributes)
         */
        System.out.println( " HandshakeInterceptor: beforeHandshake, attributes is : " + attributes );
        return super.beforeHandshake( request, response, wsHandler, attributes );
    }

    /**
     * 握手后
     */
    @Override
    public void afterHandshake(
            ServerHttpRequest request,
            ServerHttpResponse response, WebSocketHandler wsHandler,
            Exception ex
    ) {
        System.out.println(" HandshakeInterceptor: afterHandshake ");
        super.afterHandshake(request, response, wsHandler, ex);
    }
}

6. websocket处理器

处理器里面可以注入想要的service

package com.web.common.util.websocket;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.web.socket.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;


/**
 * websocket处理类就是处理:连接开始、关闭、处理信息等方法
 *
 * @author lenovo
 */
public class MyWebSocketHander implements WebSocketHandler {

    /**
     * 保存所有的用户session
     */
    private static final ArrayList users = new ArrayList();

    /**
     *  连接就绪时
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        System.out.println("connection success ...... ");
        users.add(webSocketSession);
    }

    /**
     * 处理信息
     *
     * @param webSocketSession
     * @param webSocketMessage
     * @throws Exception
     */
    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage> webSocketMessage) throws Exception {
        Gson gson = new Gson();
        Map msg = gson.fromJson(webSocketMessage.getPayload().toString(),
                new TypeToken>() {}.getType());
        // 处理消息 msgContent消息内容
        TextMessage textMessage = new TextMessage(msg.get("msgContent").toString(), true);
        System.out.println("页面传递的消息为: "+ msg.get("msgContent").toString());
        // 调用方法(发送消息给所有人)
        sendMsgToAllUsers(textMessage);
    }


    private void sendMsgToAllUsers(TextMessage textMessage) {
        System.out.println("users list is : "+users);
        for (WebSocketSession user : users) {
            try {
                user.sendMessage(textMessage);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理传输时异常
     *
     * @param webSocketSession
     * @param throwable
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        System.out.println(" Transport occur error ......");

    }

    /**
     * 关闭连接时
     *
     * @param webSocketSession
     * @param closeStatus
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        System.out.println("connection close ......");
    }

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

7. 示例页面

"text/html;charset=UTF-8" language="java" %>

"en">首页"utf-8">
    "viewport" content="width=device-width, initial-scale=1.0">
    "renderer" content="webkit">
    
    
"margin: 20px auto; border: 1px solid blue; width: 300px; height: 500px;">
"msg" style="width: 100%; height: 70%; border: 1px solid yellow;overflow: auto;">

8. 页面js

$(function() {
    var websocket;
    // 首先判断是否 支持 WebSocket
    if(WebSocket in window) {
        websocket = new WebSocket("ws://localhost:9092/WebSocketProGram/visualizationWebSocket.do");
    } else if(MozWebSocket in window) {
        websocket = new MozWebSocket("ws://localhost:9092/WebSocketProGram/visualizationWebSocket.do");
    } else {
        websocket = new SockJS("http://localhost:9092/WebSocketProGram/sockjs/visualizationWebSocket.do");
    }
    // 打开时
    websocket.onopen = function(evnt) {
        console.log("websocket.onopen  ");
    };
    // 处理消息时
    websocket.onmessage = function(evnt) {
        $("#msg").append("

(

" + evnt.data + ")"); console.log(" websocket.onmessage "); }; websocket.onerror = function(evnt) { console.log(" websocket.onerror "); }; websocket.onclose = function(evnt) { console.log(" websocket.onclose "); }; // 点击了发送消息按钮的响应事件 $("#TXBTN").click(function(){ // 获取消息内容 var text = $("#tx").val(); // 判断 if(text == null || text == ""){ alert(" content can not empty!!"); return false; } var msg = { msgContent: text, postsId: 1 }; // 发送消息 websocket.send(JSON.stringify(msg)); }); });

 

spring整合websocket通信

标签:example   参考   can   token   resources   inf   int   win   ble   

原文地址:https://www.cnblogs.com/sunfie/p/9614034.html


评论


亲,登录后才可以留言!