美文网首页Java 杂谈Spring-Boot
Spring Boot + DD小程序 超级简单的websco

Spring Boot + DD小程序 超级简单的websco

作者: 九草 | 来源:发表于2018-12-25 15:17 被阅读136次
    任务目标:
        实现移动端两个不同页面间的实时传值。
    操作环境:
         Spring Boot     钉钉小程序开发工具
    最终效果如下图:

按照个人理解来说,把本地(127.0.0.1)作为服务器端,然后里面有个webscoket组,打开A项目中的页面A后以及B项目的页面B,A、B连接进去了webscoket,然后点击A页面的按钮后,给后端发一条消息数据,后端发送这条消息数据给webscoket中的所有人,这时候B收到了消息,经过判断消息数据后,展示弹出框效果。

钉钉开发文档中有介绍webscoket,但是没有后端接口的实现列子,这让我很难受。不过看了看,发现前端很容易写出来,于是先不管接口怎么实现,把前端弄出来。
文档地址连接

先写A页面,新建了一个项目,创建了页面ws1。

#axml就直接加了按钮
<view>
      <button type="default" onTap="cj" >抽奖</button>
</view>



#js代码
Page({
  data: {},
  onLoad() {
    let _this = this;
    //创建一个 WebSocket 的连接
    dd.connectSocket({
      url: 'ws://127.0.0.1:8080/websocket', // 开发者服务器接口地址,必须是 wss 协议,且域名必须是后台配置的合法域名
      success: (res) => {
        dd.showToast({
          content: 'success', // 文字内容
        });
      },
      fail:()=>{
        dd.showToast({
          content: 'fail', // 文字内容
        });
      }
    });
    //监听WebSocket连接打开事件
    dd.onSocketOpen(function(res) {
        console.log('WebSocket 连接已打开!');
    });
    //监听WebSocket错误
    dd.onSocketError(function(res){
     console.log('WebSocket 连接打开失败,请检查!');
    });
 },
 //抽奖点击事件
 cj(){
   //发送消息
   dd.sendSocketMessage({
    data: "this is my ider", // 需要发送的内容
    success: (res) => {
        console.log("发送成功");
    },
  });
 },
});

再新建了B项目,新建了页面ws2

#页面可以没内容,直接写js
Page({
  data: {},
  onLoad() {
   let _this = this;
    dd.connectSocket({
      url: 'ws://127.0.0.1:8080/websocket', // 开发者服务器接口地址,必须是 wss 协议,且域名必须是后台配置的合法域名
      success: (res) => {
        dd.showToast({
          content: 'success', // 文字内容
        });
      },
      fail:()=>{
        dd.showToast({
          content: 'fail', // 文字内容
        });
      }
    });
    dd.onSocketOpen(function(res) {
        console.log('WebSocket 连接已打开!');
    });
    dd.onSocketError(function(res){
     console.log('WebSocket 连接打开失败,请检查!');
    });
//监听WebSocket接受到服务器的消息事件。
    dd.onSocketMessage(function(res) {
      console.log('收到服务器内容:' + res.data);
      if(res.data == "this is my ider"){
        _this.cj();
      }
    });
 },
 cj(){
    dd.alert({
        title:"恭喜你,小伙子,你中了500块砖头!!!",
    });
 }

});

前端页面代码完成,现在看一下怎么写接口。终于找到一篇能看懂的文章了。
文章地址连接

第一步:

使用springBoot创建webSocket,首先要注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。要注意,如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理。

@Configuration 
public class WebSocketConfig { 
@Bean 
    public ServerEndpointExporter serverEndpointExporter() { 
                      return new ServerEndpointExporter(); 
    }
}
第二步:

编写具体实现类。

@ServerEndpoint("/websocket")
@Component
public class WebSocket {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
     private static int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。 
     private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>(); 
     //与某个客户端的连接会话,需要通过它来给客户端发送数据
     private Session session;
     /**
      * 连接建立成功调用的方法
      * 连接时会自动调用
      */
     @OnOpen
     public void onOpen(Session session) {
         this.session = session;
         webSocketSet.add(this);  //加入set中
         addOnlineCount(); //在线数加1
         System.out.println("有新连接加入!当前在线人数为"+getOnlineCount());
         try {
             sendMessage("HEllo world");
         }catch(IOException e){
             System.out.println("io异常");
         }
     }
     /**
      * 连接关闭调用的方法
      * 关闭时自动调用
      * */
     @OnClose
     public void onClose() {
         webSocketSet.remove(this); //从set中删除
         subOnlineCount();  //在线人数减少1
         System.out.println("有一连接关闭!当前在线人数为"+getOnlineCount());
     }
     /**
      * 收到客户端消息后调用的方法
      *
      * @param message 客户端发送过来的消息
      * 客户端向服务端主动发送消息时调用
      */
     @OnMessage
     public void onMessage(String message,Session session) {
         System.out.println("来自客户端的消息:" + message);
        //群发消息 
         for (WebSocket item : webSocketSet) { 
             try { item.sendMessage(message); 
             } catch (IOException e) { 
                 e.printStackTrace(); 
                 } 
             }

     }
     
     /**
      * 发生错误时调用
      */
     @OnError 
     public void onError(Session session, Throwable error) { 
         System.out.println("发生错误"); 
         error.printStackTrace(); 
         }
   //向客户端推送消息 
     public void sendMessage(String message) throws IOException { 
         this.session.getAsyncRemote().sendText(message); 
         }
     /**
      * 群发自定义消息
      * 可以在controller中调用该方法来实时推送消息
      */ 
     public static void sendInfo(String message) throws IOException { 
         for (WebSocket item : webSocketSet) { 
             try { item.sendMessage(message); 
             } catch (IOException e) { 
                 continue; 
                 } 
             } 
         }

     public static synchronized int getOnlineCount() {
         return onlineCount; 
         } 
     public static synchronized void addOnlineCount() { 
         WebSocket.onlineCount++; 
         } 
     public static synchronized void subOnlineCount() { 
         WebSocket.onlineCount--; 
         }

}

东西写到这,其实已经结束了,运行spring boot ,再启动两个移动端后,可以发现,后端控制台会显示

   有新连接加入!当前在线人数为2

然后点击抽奖按钮后,控制台会接着输出:

  来自客户端的消息:this is my ider

GAME OVER

相关文章

网友评论

    本文标题:Spring Boot + DD小程序 超级简单的websco

    本文链接:https://www.haomeiwen.com/subject/jrrflqtx.html