简体   繁体   中英

Android Java TCP/IP server to service

I can not add TCP/IP Server to the service, when closing (minimizing) the application, the server does not accept data. How to make the data transmitted continuously?

public int onStartCommand(Intent intent, int flags, int startId) {
    myServer = new Server();
    myServer.start();  
    return Service.START_STICKY;
}

Server

 private class Server extends Thread {
    private Socket clientSocket; 
    private  ServerSocket server; 
    private  BufferedReader in; 
    private  BufferedWriter out; 
    private String LOG_TAG;

    @Override
    public void run() {
      while (true) {
            try {
                server = new ServerSocket(9002);
                clientSocket = server.accept();
                try {
                    try {
                        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                        out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
                        String word = in.readLine();
                        Log.d(LOG_TAG, "***" + word + "***");
                        out.write(word);
                        out.flush();
                    } finally {
                        System.out.println("run closed");
                        clientSocket.close();
                        in.close();
                        out.close();
                    }
                } finally {
                    System.out.println("Server closed");
                    server.close();
                }
            } catch (IOException e) {
                System.err.println(e);
            }
        }
    }
}

So many problems with this code. Here's a list of them:

  • You'd need to be a foreground service, or Android will eventually kill your service.
  • You're making a server socket and accepting a single connection to it, then making another in a loop. That's not how you do it. You make the server socket once, and accept() for each incoming connection
  • As a consequence of the above, the second time will always fail, because the port won't be immediately available unless you use a socket with SO_REUSEADDR set. see the setReuseAddress call on ServerSocket
  • You're catching all exceptions blindly. I would highly suspect you're throwing an exception and ignoring it, causing it all to not work
  • This code won't work on any cellular network, as a NAT will be put between you and the world.
  • Even on wifi you need to make sure your network allows incoming connections to your device. The default on most home routers is not to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM