netty-socketio实时推送信息

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

<dependency>
     <groupId>com.corundumstudio.socketiogroupId>
     <artifactId>netty-socketioartifactId>
     <version>1.7.7version>
dependency>

客户端使用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 clientsMap  = new HashMap();

    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)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 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;
    }
}

客户端启动服务

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

            }
        })
//启动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);
        }
    }

服务端推送数据

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

客户端接收推送数据,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);
});

你可能感兴趣的:(netty-socketio实时推送信息)