使用socket,实现小程序上的信息,实时同步到pc端

package com.njzykj.ms.support.wechatsocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.njzykj.ms.entity.wechat.ZykjAlarmAttachments;
import com.njzykj.ms.entity.wechat.ZykjWechatAlarm;
import com.njzykj.ms.service.rescue.RescueTeamService;
import com.njzykj.ms.service.wechat.AlarmAttachmentService;
import com.njzykj.ms.service.wechat.WeChatAlarmService;
import com.njzykj.ms.support.spring.ApplicationContextHelper;
import com.njzykj.ms.support.websocket.HttpSessionConfigurator;
import com.njzykj.ms.utils.UUIDGenerator;
import com.njzykj.ms.utils.redis.RedisManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/wechatSendServer", configurator = HttpSessionConfigurator.class)
public class WechatSendServer implements InitializingBean {
    protected static final Logger logger = LoggerFactory.getLogger(WechatSendServer.class);
    // 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    private static CopyOnWriteArraySet<WechatSendServer> webSocketSet = new CopyOnWriteArraySet<WechatSendServer>();
    // 与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    // 用户名
    private String userid;
    // request的session
    private HttpSession httpSession;

    private WeChatAlarmService weChatAlarmService;

    private AlarmAttachmentService alarmService;
    // 在线列表,记录用户名称
    private static List list = new ArrayList<>();
    // 用户名和websocket的session绑定的路由表
    private static Map routetab = new HashMap<>();

    /**
     * 连接建立成功调用的方法
     *
     * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this); // 从set中删除
    }

    /**
     * 接收客户端的message
     *
     * @param messages 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String messages) {
        JSONObject chat = JSON.parseObject(messages);
        JSONObject message = JSON.parseObject(chat.get("message").toString());
        /**
         * 解析message,将传过来的数据取出,保存到数据库
         */
        WechatAlarm wechatAlarm = new WechatAlarm();
            .
            .
            .
            .
            .
        message.put("createTime",wechatAlarm.getCreateTime());
        message.put("alarmId",alarmId);
        message.put("type",5);
        // 如果to为空,则广播;如果不为空,则对指定的用户发送消息
        if (message.get("to") == null ||"" .equals(message.get("to"))) {
            broadcast(message.toJSONString());
        } else {
        String[] userlist = message.get("to").toString().split(",");
            // 发送给自己,这个别忘了
        singleSend(messages, (Session) routetab.get(message.get("from")));
        for (String user : userlist) {
            // 分别发送给每个指定用户
            singleSend(messages, (Session) routetab.get(user));
            }
        }
    }

    /**
     * 广播消息
     *
     * @param message
     */
    public void broadcast(String message) {
        for (WechatSendServer chat : webSocketSet) {
            try {
                chat.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    /**
     * 对特定用户发送消息
     *
     * @param message
     * @param session
     */
    public void singleSend(String message, Session session) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 组装返回给前台的消息
     *
     * @param message 交互信息
     * @return
     */
    public String getMessage(String message) {
        JSONObject member = new JSONObject();
        member.put("message", message);
        return member.toString();
    }
    /**
     * 发生错误时调用
     * @param error
     */
    @OnError
    public void onError(Throwable error){
        error.printStackTrace();
    }

    public void addOnlineCount() {
        WechatSendServer.onlineCount++;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        weChatAlarmService = (WeChatAlarmService) ApplicationContextHelper.getBean("rescueTeamService");
        alarmService = (AlarmAttachmentService) ApplicationContextHelper.getBean("rescueTeamService");
    }

    private WeChatAlarmService getweChatAlarmService() {
        if (weChatAlarmService == null) {
            weChatAlarmService = (WeChatAlarmService) ApplicationContextHelper.getBean("weChatAlarmService");
        }
        return weChatAlarmService;
    }

    private AlarmAttachmentService getAlarmService() {
        if(alarmService == null){
            alarmService = (AlarmAttachmentService) ApplicationContextHelper.getBean("alarmService");
        }
        return alarmService;
    }
}

通过以上代码,就可以实现小程序端的信息,进行数据库存储之后,信息就会转发到pc端,pc端进行接收消息,进行展示即可

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

醉梦逍遥游

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值