ssm使用websocket

这里写图片描述
SpringMvc中socket的部分

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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:websocket="http://www.springframework.org/schema/websocket"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    <mvc:annotation-driven/> 
     <mvc:resources location="/" mapping="/**"/> 

    <bean id="myHandler" class="com.turing.websocket.WebsocketEndPoint"></bean>
    <websocket:handlers allowed-origins="*">
        <websocket:mapping path="/myHandler" handler="myHandler"/>
        <websocket:handshake-interceptors>
            <bean class="com.turing.websocket.HandshakeInterceptor"/>
        </websocket:handshake-interceptors>
    </websocket:handlers>

    <websocket:handlers allowed-origins="*">
        <websocket:mapping path="/sockjs/myHandler" handler="myHandler"/>
        <websocket:sockjs/>
    </websocket:handlers>
</beans>

applicationContext里面不用写socket的

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:websocket="http://www.springframework.org/schema/websocket"
    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-4.3.xsd
        http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket-4.3.xsd">


</beans>

pom文件中

<project xmlns="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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.turing</groupId>
  <artifactId>socket</artifactId> 
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>socket Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
    <spring.version>4.3.3.RELEASE</spring.version>
    <jackson.version>2.8.3</jackson.version>
    <plugin.maven-version>2.2</plugin.maven-version>
  </properties>

  <dependencies>
    <!-- socketJs start -->
    <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-websocket</artifactId>
           <version>${spring.version}</version>
        </dependency>
        <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-messaging</artifactId>
           <version>${spring.version}</version>
        </dependency>
        <!-- socketJs end -->


        <!-- spring start -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context-support</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <!-- spring end -->
  </dependencies>


  <build> 
    <finalName>socket</finalName>
    <!--配置Maven 对resource文件 过滤 -->
       <resources>
           <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource> 
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.java</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
              <resource>
                <directory>src/main/webapp</directory>
                <includes>
                    <include>**/*.css</include>
                    <include>**/*.html</include>
                    <include>**/*.js</include>
                    <include>**/*.jpg</include>
                    <include>**/*.jsp</include>
                    <include>**/*.ttf</include>
                    <include>**/*.woff</include>
                    <include>**/*.woff2</include>
                    <include>**/*.svg</include>
                    <include>**/*.eot</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
           <!-- tomcat插件 -->       

             <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>${plugin.maven-version}</version>
                <configuration>
                    <url>http://localhost:8080/manager/text</url>
                    <uriEncoding>UTF-8</uriEncoding>
                   <server>TomcatServer</server><!--和上面的setting文件id相同--> 
                   <path>/websocket</path>
                   <finalName>websocket</finalName>
                </configuration>
            </plugin>
        </plugins>
  </build>


</project>

握手类HandshakeeInterceptor.java

package com.turing.websocket;

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.support.HttpSessionHandshakeInterceptor;

/**
 * websocket握手类
 * @author cheny
 *
 */
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor{
        /**
         * 这个拦截器是因为使用websocket的时候springmvc获取不到session中的对象,可以在这拦截器中取出来处理
         */
      @Override
      public boolean beforeHandshake(ServerHttpRequest request,ServerHttpResponse response, WebSocketHandler wsHandler,
          Map<String, Object> attributes) throws Exception {
        System.out.println("开始拦截类");
        return super.beforeHandshake(request, response, wsHandler, attributes);
      }

      @Override
      public void afterHandshake(ServerHttpRequest request,ServerHttpResponse response, WebSocketHandler wsHandler,
          Exception ex) {
        System.out.println("结束拦截类");
        super.afterHandshake(request, response, wsHandler, ex);
      }

    }

WebsocketEndPoint.java

package com.turing.websocket;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * websocket������
 * @author cheny
 *
 */

public class WebsocketEndPoint extends TextWebSocketHandler {

      @Override
      protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);

        TextMessage returnMessage = new TextMessage(message.getPayload()+" 发送的数据");
        System.out.println("返回的信息"+returnMessage);
        session.sendMessage(returnMessage);
      }
}

页面中使用

<!DOCTYPE html>
<html>
<head>


    <meta name="content-type" content="text/html; charset=UTF-8">
  <title>WebSocket/SockJS Echo Sample (Adapted from Tomcat's echo sample)</title>
  <style type="text/css">
    #connect-container {
      float: left;
      width: 400px
    }

    #connect-container div {
      padding: 5px;
    }

    #console-container {
      float: left;
      margin-left: 15px;
      width: 400px;
    }

    #console {
      border: 1px solid #CCCCCC;
      border-right-color: #999999;
      border-bottom-color: #999999;
      height: 170px;
      overflow-y: scroll;
      padding: 5px;
      width: 100%;
    }

    #console p {
      padding: 0;
      margin: 0;
    }
  </style>

</head>
<body>

<div>
  <div id="connect-container">
    <input id="radio1" type="radio" name="group1" onclick="updateUrl('/socket/myHandler');">
      <label for="radio1">W3C WebSocket</label>
    <br>
    <input id="radio2" type="radio" name="group1" onclick="updateUrl('/socket/sockjs/myHandler');">
      <label for="radio2">SockJS</label>
    <div>
      <button id="connect" onclick="connect();">链接</button>
      <button id="disconnect" disabled="disabled" onclick="disconnect();">断开</button>
    </div>
    <div>
      <textarea id="message" style="width: 350px" placeholder="输入要发送的消息"></textarea>
    </div>
    <div>
      <button id="echo" onclick="echo();" disabled="disabled">发送消息</button>
    </div>
  </div>
  <div id="console-container">
    <div id="console"></div>
  </div>
</div>
</body>

<script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
<script type="text/javascript">
    var ws = null;
    var url = null;
    var transports = [];

    function setConnected(connected) {
      document.getElementById('connect').disabled = connected;
      document.getElementById('disconnect').disabled = !connected;
      document.getElementById('echo').disabled = !connected;
    }

    //修改url,提供了两种url一种是wbsocket的一种是sockjs的
    function updateUrl(urlPath) {
        //如果链接中有sockjs字段就让链接等于传进来的本身
      if (urlPath.indexOf('sockjs') != -1) {
        url = urlPath;
      }
      else {
        if (window.location.protocol == 'http:') {
          url = 'ws://' + window.location.host + urlPath;
        } else {
          url = 'wss://' + window.location.host + urlPath;
        }
      }
    }


    //链接握手
    function connect() {
      if (!url) {
        alert('选择一个url');
        return;
      }
        //判断链接中是否有sockjs,如果有使用sockjs的方式拼链接,如果没有发送ws链接
      if(url.indexOf('sockjs') != -1){
       //new SockJS(url, _reserved, options);默认三个参数,中间的基本不用,最后一个是sockjs提供的传输功能,参数是数组(默认是全部开启)
         ws =new SockJS(url);
      }else{
         ws= new WebSocket(url);
      }


       //打开链接
      ws.onopen = function () {
        setConnected(true);
        log('消息: 链接已打开');
      };
      //获取消息
      ws.onmessage = function (event) {
      //调用下面的现实信息的方法
        log('推送的消息: ' + event.data);
      };
      //关闭链接
      ws.onclose = function (event) {
        setConnected(false);
         //调用下面的现实信息的方法
        log('消息: 链接已关闭');
        log(event);
      };
    }

    //发送消息
    function echo() {
      if (ws != null) {
      //获取到输入框中的消息
        var message = document.getElementById('message').value;
         //调用下面的现实信息的方法
        log('发送: ' + message);
        ws.send(message);
      } else {
        alert('消息没有链接地址,请重新连接');
      }
    }

    //将传输回来的信息显示在右侧
    function log(message) {
      var console = document.getElementById('console');
      var p = document.createElement('p');
      p.style.wordWrap = 'break-word';
      p.appendChild(document.createTextNode(message));
      console.appendChild(p);
      //防止消息过长干div外面去
      while (console.childNodes.length > 25) {
        console.removeChild(console.firstChild);
      }
      //console.scrollTop = console.scrollHeight;
    }


    //关闭链接的时候将ws链接清空
    function disconnect() {
      if (ws != null) {
        ws.close();
        ws = null;
      }
      setConnected(false);
    }
  </script>
</html>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值