提供一个微信小程序和springboot长链接,后端IP是 192.168.124.20 端口号是8090,写一个微信小程序的demo,可以互相发送信息
时间: 2023-11-22 22:54:33 浏览: 87
微信小程序端可以使用wx.requestSocket进行websocket长链接通信,后端使用SpringBoot的WebSocket进行处理。以下是一个简单的demo:
1. 微信小程序端代码
```javascript
//index.js
Page({
data: {
message: '',
socketOpen: false,
inputValue: ''
},
onLoad: function () {
wx.connectSocket({
url: 'ws://192.168.124.20:8090/ws',
})
wx.onSocketOpen((res) => {
console.log('WebSocket连接已打开!')
this.setData({ socketOpen: true })
})
wx.onSocketMessage((res) => {
console.log('收到服务器内容:' + res.data)
this.setData({ message: res.data })
})
wx.onSocketClose((res) => {
console.log('WebSocket连接已关闭!')
this.setData({ socketOpen: false })
})
wx.onSocketError((res) => {
console.log('WebSocket连接打开失败,请检查!')
})
},
sendMessage: function() {
if (!this.data.inputValue) {
wx.showToast({
title: '请输入内容',
icon: 'none'
})
return
}
if (this.data.socketOpen) {
wx.sendSocketMessage({
data: this.data.inputValue,
success: () => {
console.log('发送成功!')
}
})
this.setData({ inputValue: '' })
} else {
wx.showToast({
title: '连接已断开!',
icon: 'none'
})
}
},
inputHandler: function(e) {
this.setData({ inputValue: e.detail.value })
}
})
```
2. SpringBoot端代码
WebSocketConfig.java
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "/ws")
.setAllowedOrigins("*");
}
@Bean
public WebSocketHandler myHandler() {
return new MyHandler();
}
}
```
MyHandler.java
```java
public class MyHandler implements WebSocketHandler {
private static final List<WebSocketSession> sessions = new ArrayList<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
System.out.println("新连接加入,当前在线人数:" + sessions.size());
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
String msg = message.getPayload().toString();
System.out.println("收到信息:" + msg);
for (WebSocketSession s : sessions) {
s.sendMessage(new TextMessage(msg));
}
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
if (session.isOpen()) {
session.close();
}
sessions.remove(session);
System.out.println("连接错误,当前在线人数:" + sessions.size());
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
sessions.remove(session);
System.out.println("连接关闭,当前在线人数:" + sessions.size());
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}
```
这个demo是一个简单的群聊,所有连接到服务器的客户端都会收到其他客户端发送的信息。如果需要实现点对点聊天,可以在MyHandler中对消息进行处理,只向指定的客户端发送消息。
阅读全文