Rumah > applet WeChat > Pembangunan program mini > 微信小程序websocket人如何实现SpringMVC+Spring+Mybatis的实例

微信小程序websocket人如何实现SpringMVC+Spring+Mybatis的实例

黄舟
Lepaskan: 2017-09-13 09:16:45
asal
2875 orang telah melayarinya

这篇文章主要介绍了 微信小程序websocket实现SpringMVC+Spring+Mybatis的相关资料,这里提供实现思路及实现代码,需要的朋友可以参考下

微信小程序实现websocket步骤:

后台:


 1. 添加maven依赖
 2. 创建握手
 3. 创建处理器
 4. spring配置(xml配置或javabean方式配置任选一种)
Salin selepas log masuk

微信小程序:


 1. 书写连接
Salin selepas log masuk

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>
Salin selepas log masuk

2.创建握手


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转换成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

  }

}
Salin selepas log masuk

3.创建处理器


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<>();

  // 用户进入系统监听
  @Override
  public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    System.out.println("成功进入了系统。。。");
    users.add(session);

    sendMessagesToUsers(new TextMessage("今天晚上服务器维护,请注意"));
  }

  //
  @Override
  public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
    // 将消息进行转化,因为是消息是json数据,可能里面包含了发送给某个人的信息,所以需要用json相关的工具类处理之后再封装成TextMessage,
    // 我这儿并没有做处理,消息的封装格式一般有{from:xxxx,to:xxxxx,msg:xxxxx},来自哪里,发送给谁,什么消息等等
    // TextMessage msg = (TextMessage)message.getPayload();
    // 给所有用户群发消息
    //sendMessagesToUsers(msg);
    // 给指定用户群发消息
    //sendMessageToUser(userId, msg);

  }

  // 后台错误信息处理方法
  @Override
  public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

  }

  // 用户退出后的处理,不如退出之后,要将用户信息从websocket的session中remove掉,这样用户就处于离线状态了,也不会占用系统资源
  @Override
  public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
    if (session.isOpen()) {
      session.close();
    }
    users.remove(session);
    System.out.println("安全退出了系统");

  }

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

  /**
   * 给所有的用户发送消息
   */
  public void sendMessagesToUsers(TextMessage message) {
    for (WebSocketSession user : users) {
      try {
        // isOpen()在线就发送
        if (user.isOpen()) {
          user.sendMessage(message);
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * 发送消息给指定的用户
   */
  public void sendMessageToUser(String userId, TextMessage message) {
    for (WebSocketSession user : users) {
      if (user.getAttributes().get("").equals(userId)) {
        try {
          // isOpen()在线就发送
          if (user.isOpen()) {
            user.sendMessage(message);
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
}
Salin selepas log masuk

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" />
Salin selepas log masuk

注意:

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>
Salin selepas log masuk

2 .setAllowedOrigins(“*”)中的*代表合法的请求域名,该方法接受一个可变数组作为参数,一定要配置,不然会请求时会出现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>
Salin selepas log masuk

2.websocket.js


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

 /**
  * 页面的初始数据
  */
 data: {

 },
 connectWebsocket: function () {
  wx.connectSocket({
   url: &#39;ws://localhost:8080/AhutShop/webSocketServer.action&#39;,
   data: {
   },
   header: {
    &#39;content-type&#39;: &#39;application/json&#39;
   },
   method: "GET"
  })
  wx.onSocketOpen(function (res) {
   console.log(&#39;WebSocket连接已打开!&#39;)
  })
  wx.onSocketError(function (res) {
   console.log(&#39;WebSocket连接打开失败,请检查!&#39;)
  })
  wx.onSocketMessage(function (res) {
   console.log(&#39;收到服务器内容:&#39; + res.data)
  })
 }
})
Salin selepas log masuk

运行效果

Atas ialah kandungan terperinci 微信小程序websocket人如何实现SpringMVC+Spring+Mybatis的实例. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan