0

我已经在 android 上实现了 Socket.io 客户端,我设法在无界服务中初始化了套接字,但问题是当应用程序处于后台并且手机被锁定时,它在 5 分钟后断开连接。如果应用程序在前台,则连接保持无休止。

断线情况:

  1. 服务仍在运行
  2. 套接字由于未知原因而断开连接
  3. 套接字实例是在 Singelton 类中创建的,并且该实例在生命周期中始终保持不变,我已经检查了套接字实例的哈希码。
  4. 我也实施了 Ping Pong 解决方案,但它不起作用。
  5. 检查服务器日志,发现用户的套接字已断开。
  6. 我什至尝试重新启动服务,但重新启动后没有连接。
  7. 再次连接套接字以终止应用程序并重新启动应用程序的唯一方法。

MySingelton.java

public class Singelton implements Serializable {
    private static Singelton instance;
    private static final String SERVER_ADDRESS = "xyz";
    private Socket mSocket;
    private Context context;

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

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

    private static synchronized Singelton getSync(Context context) {
        if(instance == null){
            instance = new Singelton(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);
        }
    }
}

我的服务

public class MessageService extends Service {
    Socket mSocket;
    
    public MessageService() {
        mSocket = Singelton.get(this).getSocket();
        Log.d("chat", "Constructor"+String.valueOf(mSocket.hashCode()));
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("chat", "onStartCommand"+String.valueOf(mSocket.hashCode()));
        initSocket();
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
        wl.acquire();
        //Log.e(TAG, "onStartCommand");
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Log.d("chat", "onDestroyed");
        Calendar cal = Calendar.getInstance();
        Intent intent = new Intent(getApplicationContext(), MessageService.class);
        PendingIntent pintent = PendingIntent.getService(MessageService.this, 0, intent, 0);
        AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+(1*1000), pintent);

        super.onDestroy();
    }

    @Override
    public void onCreate() {
        Log.d("chat", "onCreate");
        super.onCreate();
    }

    private void initSocket(){
        mSocket.on(Socket.EVENT_CONNECT,onConnect);
        mSocket.on(Socket.EVENT_DISCONNECT,onDisconnect);
        mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
        mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
        mSocket.on(Socket.EVENT_RECONNECT, onReconnect);
        mSocket.on("pingy", ping);      
        mSocket.connect();
        mSocket.emit("pongy", "Hi");
    }
    int i=0;
    Emitter.Listener ping = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Log.d("chat", String.valueOf(i) + " " + mSocket.hashCode());
            i++;
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    new CountDownTimer(2000,1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {

                        }

                        @Override
                        public void onFinish() {
                            mSocket.emit("pongy", "Hi");                           
                        }
                    }.start();
                }
            });
        }
    };

    Emitter.Listener onConnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Log.d("chat", "connected");
        }
    };
    Emitter.Listener onReconnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Log.d("chat", "onReconnect");
        }
    };
    Emitter.Listener onDisconnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            //mSocket.disconnect();
            Log.d("chat", "onDisconnect");
            stopSelf();
        }
    };
    Emitter.Listener onConnectError = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Log.d("chat", args[0].toString());
        }
    };
    
    
    
    
    
    

    

    

 
}

注意:我想让服务一直在后台运行,它不应该被系统或应用程序杀死

  • 我需要为此实施远程服务吗?
  • 如果它是一个远程服务,它应该是有界的还是无界的?
4

0 回答 0