微信小程序websocket的java例子demo
这是用java实现的微信小程序websocket小例子。我也是第一次接触,本人亲自实践,用上该例子能节省初学者3小时的找资料时间
工具/原料
微信web开发者工具
java代码
1、创建工程websocketTest,只需一个类TestWebSocket,需要引用tomcat7以下的websocket-api.jar,没有的可以用mavan下载<dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency>


2、java 代码:(如果蹲赓忧甘被压缩了,请查看文章结尾的引用或图片)package test;import java.io.IOException; import java.util.concurrent.CopyOnWriteArraySet; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; /** * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端, * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端 */ @ServerEndpoint("/websocket") public class TestWebSocket { //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 private static int onlineCount = 0; //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识 private static CopyOnWriteArraySet<TestWebSocket> webSocketSet = new CopyOnWriteArraySet<TestWebSocket>(); //与某个客户端的连接会话,需要通过它来给客户端发送数据 private Session session; /** * 连接建立成功调用的方法 * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据 */ @OnOpen public void onOpen(Session session){ this.session = session; webSocketSet.add(this); //加入set中 addOnlineCount(); //在线数加1 System.out.println("有新连接加入!当前在线人数为" + getOnlineCount()); } /** * 连接关闭调用的方法 */ @OnClose public void onClose(){ webSocketSet.remove(this); //从set中删除 subOnlineCount(); //在线数减1 System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount()); } /** * 收到客户端消息后调用的方法 * @param message 客户端发送过来的消息 * @param session 可选的参数 */ @OnMessage public void onMessage(String message, Session session) { String serverMsg = "你好,小程序!"; System.out.println("来自客户端的消息:" + message); //群发消息 for(TestWebSocket item: webSocketSet){ try { item.sendMessage(serverMsg); } catch (IOException e) { e.printStackTrace(); continue; } } } /** * 发生错误时调用 * @param session * @param error */ @OnError public void onError(Session session, Throwable error){ System.out.println("发生错误"); error.printStackTrace(); } /** * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。 * @param message * @throws IOException */ public void sendMessage(String message) throws IOException{ this.session.getBasicRemote().sendText(message); //this.session.getAsyncRemote().sendText(message); } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { TestWebSocket.onlineCount++; } public static synchronized void subOnlineCount() { TestWebSocket.onlineCount--; } }



3、微信端代码web-socket颍骈城茇-mytest.jsvar app = getApp()function showSuccess(title) {wx.showToast({ title, 足毂忍珩icon: 'success', duration: 1000})}Page({data: { socketStatus: 'closed', loading: false},onLoad: function () { var thisvar = this wx.onSocketOpen(function (res) { console.log('WebSocket连接已打开!') }) wx.onSocketError(function (res) { console.log('WebSocket连接打开失败,请检查!') }) wx.onSocketMessage(function (res) { console.log('收到服务器内容:' + res.data) showSuccess('发送成功') thisvar.setData({ loading: true }) }) wx.onSocketClose(function (res) { console.log('WebSocket 已关闭!') })},toggleSocket: function (e) { const turnedOn = e.detail.value var socketStatus = 'closed' console.log("turnedOn:" + turnedOn) if(turnedOn) { socketStatus = 'connected' wx.connectSocket({ url: 'ws://localhost:8080/websocketTest/websocket' }) } else { socketStatus = 'closed'; console.log('WebSocket手动关闭!') wx.closeSocket(); } this.setData({ socketStatus: socketStatus })},sendMessage : function (e) { var msg = '你好, 服务器'; if (this.data.socketStatus = 'connected') { wx.sendSocketMessage({ data: msg }) console.log('向服务器发送消息:' + msg) this.setData({ loading: true }) } else { socketMsgQueue.push(msg) }}})

4、微信端代码web-socket-mytest.wxml<import src="../../../common/head.wxml" /><import src="../../../common/foot.wxml" /><view class="container"><template is="head" data="{{title: 'WebSocket'}}"/><view class="page-body"> <view class="page-section"> <view class="weui-cells weui-cells_after-title"> <view class="weui-cell weui-cell_switch"> <view class="weui-cell__bd">Socket状态</view> <view class="weui-cell__ft"> <switch bindchange="toggleSocket" /> </view> </view> <view class="weui-cell"> <view class="weui-cell__bd">消息</view> <view class="weui-cell__ft"> Hello, 小程序! </view> </view> </view> </view> <view class="btn-area"> <button type="primary" size="40" bindtap="sendMessage" disabled="{{socketStatus != 'connected'}}" loading="{{loading}}">点我发送</button> </view></view><template is="foot" /></view>
5、点击开启“socke"状态,然后点击”点我发送“,发到服务器端,完成流程操作


