您的位置:首页 > 移动开发 > 微信开发

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

2018-12-19 15:05 525 查看
[code]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端进行接收消息,进行展示即可

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐