欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

微信小程序 websocket 实现SpringMVC+Spring+Mybatis

程序员文章站 2022-05-14 19:16:56
微信小程序实现websocket步骤: 后台: 1. 添加maven依赖 2. 创建握手 3. 创建处理器 4. spring配置(xml配...

微信小程序实现websocket步骤:

后台:

 1. 添加maven依赖
 2. 创建握手
 3. 创建处理器
 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.创建握手

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

  }

}

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

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

 /**
  * 页面的初始数据
  */
 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('收到服务器内容:' + res.data)
  })
 }
})

运行效果

微信小程序 websocket 实现SpringMVC+Spring+Mybatis

以上就是微信小程序 后台的建立,如有疑问请留言或者到本站社区交流讨论,本站关于微信小程序的文章还有很多,希望大家多多搜索查阅,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!