webSocket

webSocket protocol 是html5 一种新的协议。它实现了浏览器与服务器全双工通信,一开始的
握手需要借助http请求完成。

传统的socket是一个长链接:   客户端:(先连接上去)
                            服务端:
socket 好处:可以实现客户端和服务端双向通信
       缺点:如果大家都不说话,浪费资源


webSocket:长连接(TCP)   websocket通信的客户端必须是浏览器。
SocketJS 是一个浏览器上运行的javaScript库。
web.xml
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
  <!-- WebSocket 需要Servlet3.0 需要web.xml 3.0及以上,并要配置此 -->
  <absolute-ordering />


  <!-- springMVC 配置    start -->


  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springMVC.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <!--并且必须将所以的filter和servlet都要添加异步-->
    <async-supported>true</async-supported>
  </servlet>


  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


  <!-- springMVC 配置    end -->


  <display-name>Archetype Created Web Application</display-name>
</web-app>
pom.xml
<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.3.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.3.0</version>
    </dependency>
    <!-- springMVC begin -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.0.2.RELEASE</version>
    </dependency>


    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>4.0.2.RELEASE</version>
    </dependency>


    <!-- springMVC end -->
    <!-- WebSocket -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-websocket</artifactId>
      <version>4.0.2.RELEASE</version>
    </dependency>


    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-messaging</artifactId>
      <version>4.0.2.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
  </dependencies>

1、首先创建webSocket的处理类    implements WebSocketHandler



import java.util.ArrayList;
import java.util.Map;


import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class MyWebSocketHandler implements WebSocketHandler {

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

//连接 就绪时
public void afterConnectionEstablished(WebSocketSession session) throws Exception {

users.add(session);
}
    //处理信息
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
Gson gson=new Gson();
//将消息的json格式通过GSON转换成map
//message.getPayload().toString()  获取消息的具体内容
Map<String, Object> msg=gson.fromJson(message.getPayload().toString(),new TypeToken<Map<String, Object>>() {}.getType());
System.out.println("获取的消息是"+message.getPayload());
//session.sendMessage(message);
//处理消息 magContent消息内容
TextMessage textMessage=new TextMessage(msg.get("msgContent").toString(),true);
//调用方法(发送消息给所有人)
sendMsgToAllUsers(textMessage);
}
   //处理传送时异常
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {


}
  //关闭 连接时
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {

users.remove(session);
}


public boolean supportsPartialMessages() {

return false;
}
   //给所有用户发送消息
public void sendMsgToAllUsers(WebSocketMessage<?> message)throws Exception{
for (WebSocketSession user : users) {
            user.sendMessage(message);
        }
}
}

2、创建握手(handshake) 接口/拦截器    extends HttpSessionHandshakeInterceptor



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;
//创建握手(handshake)接口/拦截器
/*
 * 这个的主要作用是可以在握手前做一些事,把所需要的东西放入到attributes里面,
 * 然后可以在WebSocketHandler的session中, 取到相应的值,具体可参考HttpSessionHandshakeInterceptor,
 * 这儿也可以实现HandshakeInterceptor 接口
 */
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor{
//握手前
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
System.out.println("握手前 beforeHandshake"+request.getBody().toString());
return super.beforeHandshake(request, response, wsHandler, attributes);
}
//握手后
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Exception ex) {
System.out.println("握手后 afterHandshake");
super.afterHandshake(request, response, wsHandler, ex);
}



}

3、注册处理类及握手接口



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;




@Configuration
@EnableWebMvc
@EnableWebSocket
public class MyWebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {




        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {


            //前台 可以使用websocket环境
            registry.addHandler(myWebSocketHandler(),"/websocket").addInterceptors(new HandshakeInterceptor());




          //前台 不可以使用websocket环境,则使用sockjs进行模拟连接
            registry.addHandler(myWebSocketHandler(), "/sockjs/websocket").addInterceptors(new HandshakeInterceptor())
                    .withSockJS();
        }




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




}

4、websocket的js 


$(function() {


    var websocket;




    // 首先判断是否 支持 WebSocket   前两种浏览器自带
    if('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/SECIMS/websocket");
    } else if('MozWebSocket' in window) {
    //火狐
        websocket = new MozWebSocket("ws://localhost:8080/SECIMS/websocket");
    } else {
        websocket = new SockJS("http://localhost:8080/SECIMS/sockjs/websocket");
    }


    // 打开时
    websocket.onopen = function(evnt) {
        console.log("  websocket.onopen  ");
    };




    // 处理消息时
    websocket.onmessage = function(evnt) {
        $("#msg").append("<p>(<font color='red'>" + evnt.data + "</font>)</p>");
        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));


    });




});

5、在springMVC.xml中写

<?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    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/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-4.0.xsd 
            http://www.springframework.org/schema/aop 
            http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 
            http://www.springframework.org/schema/websocket
            http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd">
<context:component-scan base-package="com.fei.websocket" />


</beans>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞腾创客

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值