Socket.IO断流问题

FIXED THE BUG!
The nature of Socket IO is that the sockets timeout (or in this case, DISCONNECTS) if there are no activities present in the socket. When your phone goes to idle mode (when it sleeps), there is no constant connection that checks whether the app is active or not. One simple way to keep the socket alive is to send constant heartbeats (or ping pongs) every 20-30 seconds or so!

Server-side:

io.sockets.on('connection', function (socket) {
    socket.on('pong', function(data){
        console.log("Pong received from client");
    });
    setTimeout(sendHeartbeat, 25000);

    function sendHeartbeat(){
        setTimeout(sendHeartbeat, 25000);
        io.sockets.emit('ping', { beat : 1 });
    }
});

Client-Side:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSocket.connect();
    mSocket.on("ping", sendPong);
}

private Emitter.Listener sendPong = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    JSONObject data = (JSONObject) args[0];
                    String ping;
                    try {
                        ping = data.getString("ping");
                    } catch (JSONException e) {
                        return;
                    }
                    if(ping.equals("1")){
                        SocketSingleton.get(getApplicationContext()).getSocket().emit("pong", "pong");
                    }
                    Log.e("SOCKETPING", "RECEIVED PING! ");
                }
            });
        }
    };

This WILL work! And this does NOT drain battery! This is the BEST fix I have found so far!

 

In my experience, I do not think u need to establish a Singleton method if you have only ONE activity. You can open the connection in your main class, and turn on and off sockets in your fragment. And of course, turn off the sockets on onDestroy method in your fragment classes. I just used Singleton as a security to make sure I don't create multiple instances if Android somehow screws up.

So, here is my Singleton class:


public class SocketSingleton {
    private static SocketSingleton instance;
    private static final String SERVER_ADDRESS = "http://YOUR_ADDRESS:PORT/";
    private Socket mSocket;
    private Context context;

    public SocketSingleton(Context context) {
        this.context = context;
        this.mSocket = getServerSocket();
    }

    public static SocketSingleton get(Context context){
        if(instance == null){
            instance = getSync(context);
        }
        instance.context = context;
        return instance;
    }

    private static synchronized SocketSingleton getSync(Context context) {
        if(instance == null){
            instance = new SocketSingleton(context);
        }
        return instance;
    }

    public Socket getSocket(){
        return this.mSocket;
    }

    public Socket getServerSocket() {
        try {
            IO.Options opts = new IO.Options();
            opts.forceNew = true;
            opts.reconnection = true;
            mSocket = IO.socket(SERVER_ADDRESS, opts);
            return mSocket;
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
}

And my MainActivity:



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SocketSingleton.get(this).getSocket().connect();
        SocketSingleton.get(getApplicationContext()).getSocket().emit("joinSocket", SEND_USER_ID);

        /// Send pongs to keep connection active;
        SocketSingleton.get(this).getSocket().on("ping", sendPong);

        SocketSingleton.get(this).getSocket().on(Socket.EVENT_RECONNECT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                SocketSingleton.get(getApplicationContext()).getSocket().emit("joinSocket", SEND_USER_ID);
            }
        });
    }

    private Emitter.Listener sendPong = new Emitter.Listener() {

        @Override
        public void call(final Object... args) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    JSONObject data = (JSONObject) args[0];
                    String ping;
                    try {
                        ping = data.getString("ping");
                    } catch (JSONException e) {
                        return;
                    }
                    if(ping.equals("1")){
                        SocketSingleton.get(getApplicationContext()).getSocket().emit("pong", current_user);
                    }
                    ping_counter++;
                    Log.e("SOCKETPING", "RECEIVED PING: " + ping_counter);
                    TextView pingReceived = (TextView) findViewById(R.id.pingReceived);
                    try{
                        pingReceived.setText(ping_counter + "");
                    } catch (Exception e) {

                    }
                }
            });
        }
    };

Hope this helped you! also, if you make this code better, please do consider sharing. Thanks.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值