netty-socketio实时推送信息

之前使用做项目使用到实时推送的技术,websocket需要ie9,tomcat7,jdk7以上,兼容性不够好,因此转而使用了netty-socketio,在git上的项目地址。使用maven添加netty的jar包

<dependency>
     <groupId>com.corundumstudio.socketio</groupId>
     <artifactId>netty-socketio</artifactId>
     <version>1.7.7</version>
</dependency>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5

客户端使用socket.io,首先启动server,推送消息时服务端获取客户端,向客户端发送消息。客户端接收消息后刷新页面数据。

import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.ConnectListener;
import com.yinhai.jiankong.util.MonitorConfigUtil;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/5/18.
 */
@Service("socketIoService")
public class SocketIoService {
    static SocketIOServer server;
    static Map<String,SocketIOClient> clientsMap  = new HashMap<String, SocketIOClient>();

    public void startServer()throws InterruptedException{
        Configuration config = new Configuration();
        //服务器主机ip
        String hostName = MonitorConfigUtil.getProperties("socketHostName");
        config.setHostname(hostName);
        //端口
        int socketPort = Integer.parseInt(MonitorConfigUtil.getProperties("socketPort"));
        config.setPort(socketPort);
        config.setMaxFramePayloadLength(1024 * 1024);
        config.setMaxHttpContentLength(1024 * 1024);
        server = new SocketIOServer(config);

        //添加客户端连接事件
        server.addConnectListener(new ConnectListener() {
            @Override
            public void onConnect(SocketIOClient client) {
                String sa = client.getRemoteAddress().toString();
                String clientIp = sa.substring(1,sa.indexOf(":"));//获取设备ip
                /*System.out.println(clientIp+"-------------------------"+"客户端已连接");*/
                Map params = client.getHandshakeData().getUrlParams();

                //获取客户端连接的uuid参数
                Object object = params.get("uuid");
                String uuid = "";
                if(object != null){
                    uuid = ((List<String>)object).get(0);
                    //将uuid和连接客户端对象进行绑定
                    clientsMap.put(uuid,client);
                }
                //给客户端发送消息
                client.sendEvent("connect_msg",clientIp+"客户端你好,我是服务端,能帮助你吗?");
            }
        });
        server.start();
        Thread.sleep(Integer.MAX_VALUE);
        server.stop();
    }


    /**
     *  给所有连接客户端推送消息
     * @param eventType 推送的事件类型
     * @param message  推送的内容
     */
    public void sendMessageToAllClient(String eventType,String message){
        Collection<SocketIOClient> clients = server.getAllClients();
        for(SocketIOClient client: clients){
            client.sendEvent(eventType,message);
        }
    }

    /**
     * 停止服务
     */
    public void stopServer(){
        if(server != null){
            server.stop();
            server = null;
        }
    }

    public static SocketIOServer getServer() {
        return server;
    }
}

   
   
  • 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
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86

客户端启动服务

var socketUrl = "<%=path%>/startServer.do";
        $.ajax({
            url:socketUrl,
            type:'get',
            success:function(){

            }
        })
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
//启动socket 服务
    @RequestMapping(value = "startServer.do")
    public void startServer(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", "*");
        try {
            if (serviceIo.getServer() == null) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            serviceIo.startServer();
                        } catch (InterruptedException e) {
                            logger.error(e);
                        }
                    }
                }).start();
            }
        } catch (Exception e) {
            logger.error(e);
        }
    }
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

服务端推送数据

serviceIo.sendMessageToAllClient("advert_data", JSonFactory.bean2json(data));

   
   
  • 1
  • 2

客户端接收推送数据,socket.io.js在git上可下载

<script type="text/javascript" src="<%=basePath%>/resources/js/socketio/socket.io.js"></script>

var socket = io.connect('http://192.168.31.141:9092');
socket.on('advert_data',function(data){
    var personInfo = JSON.parse(data);
    console.log(personInfo);
});
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值