首先小程序连接websocket 并发送用户openid到服务器
wx.connectSocket({
url: "ws://192.168.1.104:9090/xcxmvc/so",
})
//连接成功
wx.onSocketOpen(function () {
console.log("c" + that.data.openid);
wx.sendSocketMessage({
data: that.data.openid,
})
})
wx.onSocketMessage(function (res) {
var objData = JSON.parse(res.data);
console.log(objData);
that.setData({ nr: objData });
})
//连接失败
wx.onSocketError(function () {
console.log('websocket连接失败!');
})
服务器接收到openid后 开启定时器 查询用户有没有收到回复
每隔一秒查询一次
如果有 并且session没被关闭
将推送消息给客户端
这里需要做个判断
如果session.isopen为true 将消息发送给客户端
否则将定时器停止
if(s.isOpen()){
try {
s.getBasicRemote().sendText(jsonObject);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.print("fa song cuo le");
}
}
else{
System.out.print("fa song cuo le");
idd=1;
cancel();
}
@OnMessage
public void onmessage(final String data,final Session s){
System.out.println(data+s.getId());
final String shou="shoudao";
String panduan="s";
TimerTask task = new TimerTask() { //创建一个新的timer task
public void run() { //定时器任务执行的操作
Gson gson = new Gson();
dao dd= new dao();
HashMap<String,List> aa=new HashMap<String,List>();
// List aa=null;
// nrbean n=new nrbean();
// List chakan=new ArrayList();
List<nrbean> li=new ArrayList<nrbean>();// po=null;
li=dd.chakan(data);
String jsonObject="";
///通过下面方法能取出list中想要的内容
// for(int i=0;i<li.size();i++){
// int id;
// nrbean nb=li.get(i);
// id=nb.getChakancichu();
// if(id==1){}
jsonObject = gson.toJson(li);
System.out.print("------------"+s.isOpen());
// }
if(s.isOpen()){
try {
s.getBasicRemote().sendText(jsonObject);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.print("fa song cuo le");
}
}
else{
System.out.print("fa song cuo le");
idd=1;
cancel();
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("现在是:" +data+"..."+s.getId());
}};
Timer timer = new Timer();//创建一个定时器
long delay = 0;
long PeriodTime = 1 * 1000;
//重复执行特定任务,第一个参数为要执行的任务,第二个为执行任务之前延迟的时间,第三个为时间间隔
//单位都是毫秒
//timer.
timer.scheduleAtFixedRate(task, delay, PeriodTime);
}
}
当小程序页面onHide时 执行关闭socket
onHide:function(){
wx.closeSocket({
})// {
},
这时服务器端执行
@OnClose
public void end() {
System.out.print("走了");
}