欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

微信小程序 websocket 實現(xiàn)SpringMVC+Spring+Mybatis

 更新時間:2017年08月04日 09:23:04   投稿:lqh  
這篇文章主要介紹了 微信小程序websocket實現(xiàn)SpringMVC+Spring+Mybatis的相關資料,這里提供實現(xiàn)思路及實現(xiàn)代碼,需要的朋友可以參考下

微信小程序?qū)崿F(xiàn)websocket步驟:

后臺:

 1. 添加maven依賴
 2. 創(chuàng)建握手
 3. 創(chuàng)建處理器
 4. spring配置(xml配置或javabean方式配置任選一種)

微信小程序:

 1. 書寫連接

java后臺

1.添加maven依賴

 <!-- websocket -->
  <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>

  <!-- 其中spring版本 -->
  <!-- 注意spring版本一定要為4以上版本 -->
  <spring.version>4.3.7.RELEASE</spring.version>

2.創(chuàng)建握手

package com.ahutshop.websocket;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * 此類用來獲取登錄用戶信息并交由websocket管理
 */
public class MyWebSocketInterceptor implements HandshakeInterceptor {

  @Override
  public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse arg1, WebSocketHandler arg2,
      Map<String, Object> arg3) throws Exception {
    // 將ServerHttpRequest轉(zhuǎn)換成request請求相關的類,用來獲取request域中的用戶信息
    if (request instanceof ServletServerHttpRequest) {
      ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
      HttpServletRequest httpRequest = servletRequest.getServletRequest();

    }

    System.out.println("連接到我了");

    return true;
  }

  @Override
  public void afterHandshake(ServerHttpRequest arg0, ServerHttpResponse arg1, WebSocketHandler arg2, Exception arg3) {
    // TODO Auto-generated method stub

  }

}

3.創(chuàng)建處理器

package com.ahutshop.websocket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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;

public class WebSocketPushHandler implements WebSocketHandler {
  private static final List<WebSocketSession> users = new ArrayList<>();

  // 用戶進入系統(tǒng)監(jiān)聽
  @Override
  public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    System.out.println("成功進入了系統(tǒng)。。。");
    users.add(session);

    sendMessagesToUsers(new TextMessage("今天晚上服務器維護,請注意"));
  }

  //
  @Override
  public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
    // 將消息進行轉(zhuǎn)化,因為是消息是json數(shù)據(jù),可能里面包含了發(fā)送給某個人的信息,所以需要用json相關的工具類處理之后再封裝成TextMessage,
    // 我這兒并沒有做處理,消息的封裝格式一般有{from:xxxx,to:xxxxx,msg:xxxxx},來自哪里,發(fā)送給誰,什么消息等等
    // TextMessage msg = (TextMessage)message.getPayload();
    // 給所有用戶群發(fā)消息
    //sendMessagesToUsers(msg);
    // 給指定用戶群發(fā)消息
    //sendMessageToUser(userId, msg);

  }

  // 后臺錯誤信息處理方法
  @Override
  public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

  }

  // 用戶退出后的處理,不如退出之后,要將用戶信息從websocket的session中remove掉,這樣用戶就處于離線狀態(tài)了,也不會占用系統(tǒng)資源
  @Override
  public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
    if (session.isOpen()) {
      session.close();
    }
    users.remove(session);
    System.out.println("安全退出了系統(tǒng)");

  }

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

  /**
   * 給所有的用戶發(fā)送消息
   */
  public void sendMessagesToUsers(TextMessage message) {
    for (WebSocketSession user : users) {
      try {
        // isOpen()在線就發(fā)送
        if (user.isOpen()) {
          user.sendMessage(message);
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * 發(fā)送消息給指定的用戶
   */
  public void sendMessageToUser(String userId, TextMessage message) {
    for (WebSocketSession user : users) {
      if (user.getAttributes().get("").equals(userId)) {
        try {
          // isOpen()在線就發(fā)送
          if (user.isOpen()) {
            user.sendMessage(message);
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
}

4.spring配置

javabean方式配置(推薦)

package com.ahutshop.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
  @Override
  public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {

    registry.addHandler(WebSocketPushHandler(), "/webSocketServer.action").addInterceptors(new MyWebSocketInterceptor()).setAllowedOrigins("*");
    registry.addHandler(WebSocketPushHandler(), "/sockjs/webSocketServer.action")
        .addInterceptors(new MyWebSocketInterceptor()).withSockJS();
  }

  @Bean
  public WebSocketHandler WebSocketPushHandler() {
    return new WebSocketPushHandler();
  }

}

spring.xml中配置掃描包
<!-- 掃描包 -->
<context:component-scan base-package="com.ahutshop.websocket" />

注意:

1. /webSocketServer.action之所以要加上.action的后綴,是因為web.xmlk中配置了攔截的后綴名為.action

<!-- springmvc模塊 -->
<servlet>
  <servlet-name>DispatcherServlet</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>
  <!-- 支持異步 -->
  <async-supported>true</async-supported>
</servlet>
<servlet-mapping>
  <servlet-name>DispatcherServlet</servlet-name>
  <url-pattern>*.action</url-pattern> 
</servlet-mapping>

2 .setAllowedOrigins(“*”)中的*代表合法的請求域名,該方法接受一個可變數(shù)組作為參數(shù),一定要配置,不然會請求時會出現(xiàn)403

xml方式配置(省略)

微信小程序

1.websocket.wxml

<!--pages/websocket/websocket.wxml-->
<view class="page">
 <view class="page__hd">
 </view>
 <view class="page__bd">

 <button bindtap="connectWebsocket" type="primary">連接websocket</button>

 </view>
</view>

2.websocket.js

// pages/websocket/websocket.js
Page({

 /**
  * 頁面的初始數(shù)據(jù)
  */
 data: {

 },
 connectWebsocket: function () {
  wx.connectSocket({
   url: 'ws://localhost:8080/AhutShop/webSocketServer.action',
   data: {
   },
   header: {
    'content-type': 'application/json'
   },
   method: "GET"
  })
  wx.onSocketOpen(function (res) {
   console.log('WebSocket連接已打開!')
  })
  wx.onSocketError(function (res) {
   console.log('WebSocket連接打開失敗,請檢查!')
  })
  wx.onSocketMessage(function (res) {
   console.log('收到服務器內(nèi)容:' + res.data)
  })
 }
})

運行效果

以上就是微信小程序 后臺的建立,如有疑問請留言或者到本站社區(qū)交流討論,本站關于微信小程序的文章還有很多,希望大家多多搜索查閱,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

相關文章

  • JS面向?qū)ο笾畣芜x框?qū)崿F(xiàn)

    JS面向?qū)ο笾畣芜x框?qū)崿F(xiàn)

    這篇文章主要為大家詳細介紹了JS面向?qū)ο笾畣芜x框?qū)崿F(xiàn),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-01-01
  • JavaScript 實現(xiàn)下雪特效的示例代碼

    JavaScript 實現(xiàn)下雪特效的示例代碼

    這篇文章主要介紹了JavaScript 實現(xiàn)下雪特效的示例代碼,幫助大家利用JavaScript制作特效,感興趣的朋友可以了解下
    2020-09-09
  • 微信小程序全局文件的使用詳解

    微信小程序全局文件的使用詳解

    在小程序開發(fā)時,每個頁面都對應一個目錄,每個目錄又分別有wxml、wxss、js和json四個文件。詳細說明可查看后續(xù)文章介紹,本文主要詳解全局文件
    2022-08-08
  • 生產(chǎn)制造追溯系統(tǒng)之在線打印功能

    生產(chǎn)制造追溯系統(tǒng)之在線打印功能

    這篇文章主要介紹了生產(chǎn)制造追溯系統(tǒng)之在線打印功能,本文圖文并茂給大家介紹的非常詳細,具有一定的參考借鑒價值 ,需要的朋友可以參考下
    2019-06-06
  • JS運動相關知識點小結(jié)(附彈性運動示例)

    JS運動相關知識點小結(jié)(附彈性運動示例)

    這篇文章主要介紹了JS運動相關知識點,總結(jié)分析了JavaScript運動所涉及的相關知識點與注意事項,并附帶了一個JavaScript彈性運動的實例供大家參考,需要的朋友可以參考下
    2016-01-01
  • uni-app微信小程序下拉多選框?qū)嵗a

    uni-app微信小程序下拉多選框?qū)嵗a

    這篇文章主要給大家介紹了關于uni-app微信小程序下拉多選框的相關資料,在通過uniapp做app開發(fā)的時候,有場景需要用到下拉選擇框,需要的朋友可以參考下
    2023-08-08
  • JavaScript操作CSS的高級用法分享

    JavaScript操作CSS的高級用法分享

    Web開發(fā)中,JavaScript與CSS的結(jié)合用于增強網(wǎng)頁的交互性和用戶體驗,本文將探索幾種高級方法來使用JavaScript操作CSS,并分別通過代碼示例進行講解,希望對大家有所幫助
    2023-12-12
  • JS實現(xiàn)隨機抽獎小功能

    JS實現(xiàn)隨機抽獎小功能

    這篇文章主要為大家詳細介紹了JS實現(xiàn)隨機抽獎小功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-01-01
  • javascript實現(xiàn)復選框超過限制即彈出警告框的方法

    javascript實現(xiàn)復選框超過限制即彈出警告框的方法

    這篇文章主要介紹了javascript實現(xiàn)復選框超過限制即彈出警告框的方法,涉及復選框及警告框的操作技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-02-02
  • 一文教會你從零開始畫echarts地圖

    一文教會你從零開始畫echarts地圖

    ECharts是一個使用JavaScript實現(xiàn)的開源可視化庫,涵蓋各行業(yè)圖表,滿足各種需求,下面這篇文章主要給大家介紹了如何從零開始畫echarts地圖的相關資料,需要的朋友可以參考下
    2022-04-04

最新評論