Pu Zhibing
1 天以前 915c265ef913601c2698faaa428f96f1e09a2369
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.sinata.push.controller;
 
 
import com.alibaba.fastjson.JSON;
import com.sinata.push.util.ResultUtil;
import com.sinata.push.util.SpringUtil;
import com.sinata.push.util.applets.NettyWebSocketController;
import com.sinata.push.util.echo.NettyChannelMap;
import com.sinata.push.util.echo.NettyServerController;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@RequestMapping("/netty")
public class NettyController {
    
    @Autowired
    private NettyServerController nettyServerController;
    
    @Autowired
    private NettyWebSocketController nettyWebSocketController;
 
 
    /**
     * 向客户端推送消息
     * @param id
     * @param msg
     */
    @ResponseBody
    @PostMapping("/sendMsgToClient")
    public String sendMsgToClient(Integer id, Integer type, String msg){
        System.out.println("推送参数:" + id + "---" + type + "---" + msg);
        if(type == 1){//用户端
            ChannelHandlerContext channel = NettyChannelMap.getData("Applets" + id);//小程序
            if(null != channel){
                nettyWebSocketController.sendMsgToClient(channel, msg);
                return JSON.toJSONString(ResultUtil.success());
            }
            channel = NettyChannelMap.getData("USER" + id);
            if(null != channel){
                nettyServerController.sendMsgToClient(channel, msg);
                return JSON.toJSONString(ResultUtil.success());
            }
            return JSON.toJSONString(ResultUtil.error("推送失败-----用户id=" + id));
 
        }
 
        if(type == 2){//司机端
            System.out.println("长链接实例:" + JSON.toJSONString(NettyChannelMap.map));
            ChannelHandlerContext channel = NettyChannelMap.getData("DRIVER" + id);
            if(null != channel){
                nettyServerController.sendMsgToClient(channel, msg);
                return JSON.toJSONString(ResultUtil.success());
            }
            return JSON.toJSONString(ResultUtil.error("推送失败-----司机id=" + id));
        }
 
        return JSON.toJSONString(ResultUtil.error("推送失败"));
    }
}