溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何在spring環(huán)境中搭建websocket

發(fā)布時間:2020-11-12 16:17:45 來源:億速云 閱讀:209 作者:Leah 欄目:編程語言

今天就跟大家聊聊有關(guān)如何在spring環(huán)境中搭建websocket,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

本文基于Apach Tomcat 8.0.3+MyEclipse+maven+JDK1.7

spring4.0以后加入了對websocket技術(shù)的支持,擼主目前的項目用的是SSM(springMVC+spring+MyBatis)框架,所以肯定要首選spring自帶的websocket

1 在maven的pom.xml中加入websocket所依賴的jar包

<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-core</artifactId>
 <version>2.4.0</version>
</dependency>
<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-databind</artifactId>
 <version>2.4.0</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-websocket</artifactId>//version須和spring mvc的version保持一致,否則會出現(xiàn)問題
  <version>4.0.5.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-messaging</artifactId>
  <version>4.0.5.RELEASE</version>
</dependency>

2 更新spring-mvc.xml中namespace.xsd的版本

<beans xmlns="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.xsd
  http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd">

處理類和握手協(xié)議的spring配置(applicationContext.xml文件)

<bean id="websocket" class="com.xl.websocket.handler"/>

<websocket:handlers>
  <websocket:mapping path="/websocket" handler="websocket"/>
  <websocket:handshake-interceptors>
  <bean class="com.xl.websocket.HandshakeInterceptor"/>
  </websocket:handshake-interceptors>
   <websocket:sockjs/>
</websocket:handlers>

webconfig

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
      registry.addHandler(new HelloHandler(), "/hello").addInterceptors(new HandshakeInterceptor()).withSockJS().setHttpMessageCacheSize(20000);

    }

3 創(chuàng)建握手(handshake)接口

public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {
 @Override
 public boolean beforeHandshake(ServerHttpRequest arg0,
  ServerHttpResponse arg1, WebSocketHandler arg2,
  Map<String, Object> arg3) throws Exception {
 
 System.out.println("---- Before Handshake ----");
 return super.beforeHandshake(arg0, arg1, arg2, arg3);
 }
 
 @Override
 public void afterHandshake(ServerHttpRequest request,
  ServerHttpResponse response, WebSocketHandler wsHandler,
  Exception ex) {
 
 System.out.println("---- After Handshake ----");
 super.afterHandshake(request, response, wsHandler, ex);
 }
}

4  創(chuàng)建websocket處理類

public class HelloHandler extends TextWebSocketHandler {
 
 public static List<WebSocketSession> users;
 static{
 users = new ArrayList<WebSocketSession>();
 }
 
 @Override
  public void handleTextMessage(WebSocketSession session, TextMessage message) {
    //接收到客戶端消息時調(diào)用
    System.out.println("text message: " + session.getId() + "-" + message.getPayload());
  }

  @Override
  public void afterConnectionEstablished(WebSocketSession session)
      throws Exception {
    // 與客戶端完成連接后調(diào)用
    System.out.println("afterConnectionEstablished");
    System.out.println("getId:" + session.getId());
    System.out.println("getLocalAddress:" + session.getLocalAddress().toString());
    System.out.println("getTextMessageSizeLimit:" + session.getTextMessageSizeLimit());
    System.out.println("getUri:" + session.getUri().toString());
    System.out.println("getPrincipal:" + session.getPrincipal());
    System.out.println(soslistService.getsss());
    session.sendMessage(new TextMessage("你好"));
    
    users.add(session);
  }

  @Override
  public void handleTransportError(WebSocketSession session,
      Throwable exception) throws Exception {
    // 消息傳輸出錯時調(diào)用
    System.out.println("handleTransportError");
  }

  @Override
  public void afterConnectionClosed(WebSocketSession session,
      CloseStatus closeStatus) throws Exception {
    // 一個客戶端連接斷開時關(guān)閉
    System.out.println("afterConnectionClosed");
  }

  @Override
  public boolean supportsPartialMessages() {
    // TODO Auto-generated method stub
    return false;
  }
}

看完上述內(nèi)容,你們對如何在spring環(huán)境中搭建websocket有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI