前期准备
项目地址 https://github.com/weiangongsi/websocket 已经实现了 双人对话 和 群聊
申请一个ssl证书免费的就可以
阿里云:https://common-buy.aliyun.com/?commodityCode=cas#/buy
然后下载证书
我们需要这个 .key 文件,把该文件放在spring boot项目resources目录下,配置文件中添加
application.yml
-
-
-
-
-
-
key-store: classpath:21427867.pfx
-
key-store-password: 21427867
-
登陆微信公众平台 小程序后台 设置-》开发设置-》服务器域名
本机调试,我们还需要做一个内网映射,花生壳,路由器端口映射,dmz主机都可以。
dmz主机可以利用阿里云的域名解析接口,自己写一个服务,实时更新A记录的值为我们本机的公网ip,这就实现了动态解析的功能。
没有以上的就 点击 开发者工具-》详细-》不校验合法域名、web-view(业务域名)、TLS 版本以及 HTTPS 证书
开始
一、服务端
可以参考spring官网案例创建websocket服务端
网址:https://spring.io/guides/gs/messaging-stomp-websocket/
pom.xml 加上websocket
-
-
<groupId>org.springframework.boot</groupId>
-
<artifactId>spring-boot-starter-websocket</artifactId>
-
WebSocketConfig.java
-
package com.example.websocket.config;
-
-
import org.springframework.context.annotation.Configuration;
-
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
-
import org.springframework.scheduling.concurrent.DefaultManagedTaskScheduler;
-
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
-
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
-
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
-
-
-
-
-
-
-
-
-
-
-
@EnableWebSocketMessageBroker
-
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
-
-
-
-
-
-
-
public void configureMessageBroker(MessageBrokerRegistry config) {
-
-
config.enableSimpleBroker("/topic", "/user")
-
.setHeartbeatValue(new long[]{10000L, 10000L})
-
.setTaskScheduler(new DefaultManagedTaskScheduler());
-
-
config.setApplicationDestinationPrefixes("/app");
-
-
config.setUserDestinationPrefix("/user");
-
-
-
-
-
-
-
-
-
public void registerStompEndpoints(StompEndpointRegistry registry) {
-
-
-
-
-
registry.addEndpoint("/gs-guide-websocket").addInterceptors(new HttpHandshakeInterceptor()).setAllowedOrigins("*");
-
-
-
HttpHandshakeInterceptor.java
-
package com.example.websocket.config;
-
-
import org.springframework.http.server.ServerHttpRequest;
-
import org.springframework.http.server.ServerHttpResponse;
-
import org.springframework.web.socket.WebSocketHandler;
-
import org.springframework.web.socket.server.HandshakeInterceptor;
-
-
-
-
-
-
-
-
-
-
public class HttpHandshakeInterceptor implements HandshakeInterceptor {
-
-
-
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
-
-
-
-
-
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
-
-
-
-
SocketController.java
-
package com.example.websocket.controller;
-
-
import com.alibaba.fastjson.JSONObject;
-
import org.springframework.beans.factory.annotation.Autowired;
-
import org.springframework.messaging.handler.annotation.MessageMapping;
-
import org.springframework.messaging.simp.SimpMessageSendingOperations;
-
import org.springframework.web.bind.annotation.RequestMapping;
-
import org.springframework.web.bind.annotation.RequestMethod;
-
import org.springframework.web.bind.annotation.RestController;
-
-
import java.time.LocalTime;
-
import java.util.logging.Logger;
-
-
import static java.util.logging.Logger.getLogger;
-
-
-
-
-
-
-
-
public class SocketController {
-
-
private static final Logger log = getLogger(SocketController.class.getName());
-
-
-
SimpMessageSendingOperations simpMessageSendingOperations;
-
-
-
-
-
@MessageMapping("/message")
-
public void handleSubscribe(String msg) {
-
msg = JSONObject.parseObject(msg).getString("msg");
-
log.info("客户端发来消息:" + msg);
-
-
-
-
-
-
-
-
-
-
-
-
@RequestMapping(path = "/sendToUser", method = RequestMethod.GET)
-
public String sendToUser(String user) {
-
String payload = "指定用户" + user + "接收信息" + LocalTime.now();
-
simpMessageSendingOperations.convertAndSendToUser(user, "/message", payload);
-
-
-
-
-
-
-
-
-
-
@RequestMapping(path = "/sendToAll", method = RequestMethod.GET)
-
public String sendToUser() {
-
String payload = "群发消息" + LocalTime.now();
-
simpMessageSendingOperations.convertAndSend("/topic/greetings", payload);
-
-
-
二、小程序
引入stomp模块, 官网下载就可以了,地址:https://raw.githubusercontent.com/jmesnil/stomp-websocket/master/lib/stomp.js
js
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
var socketConnected = false;
-
-
-
-
-
-
-
-
function sendSocketMessage(msg) {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
url: 'wss://xcx.dcssn.com/gs-guide-websocket'
-
-
-
-
-
-
wx.onSocketOpen(function(res) {
-
console.log("WebSocket 连接成功")
-
-
-
-
let queueLength = messageQueue.length
-
for (let i = 0; i < queueLength; i++) {
-
const messageQueueElement = messageQueue.shift();
-
-
data: messageQueueElement
-
-
-
-
-
-
wx.onSocketMessage(function(res) {
-
-
-
-
-
wx.onSocketError(function(res) {
-
console.log("WebSocket 错误事件")
-
-
-
-
wx.onSocketClose(function(res) {
-
console.log("WebSocket 连接关闭")
-
-
-
-
-
-
-
-
var Stomp = require('../../utils/stomp.min.js').Stomp;
-
-
-
-
-
-
-
Stomp.setInterval = function(interval, f) {
-
return setInterval(f, interval);
-
-
-
Stomp.clearInterval = function(id) {
-
return clearInterval(id);
-
-
-
var stompClient = Stomp.over(ws);
-
-
-
-
stompClient.connect({}, function(callback) {
-
-
-
stompClient.subscribe('/topic/greetings', function(body, headers) {
-
console.log('收到群发消息', body);
-
-
-
-
stompClient.subscribe('/user/' + openid + '/message', function(message, headers) {
-
-
console.log('收到只发送给我的消息:', message);
-
-
-
-
-
-
stompClient.send("/app/message", {}, JSON.stringify({
-
-
-
-
-
-
项目地址 https://github.com/weiangongsi/websocket
我有一个xcx.dcssn.com的域名证书可以供群友测试使用
qq群 806893930 25个人了
请发表评论