0

I am working on app, i want to make a TCP listener. I searched many sites for help. I am getting an error of exception. Called Socket Closed Exception. MY Code and Log Cat is given Below.

 public class ListenerService  extends Service {

//Socket socket;
private ServerSocket serverSocket;
BufferedReader in = null;
static String message=null;
int portNo=1619;
boolean flag=true;
final static String MY_ACTION = "MY_ACTION";
@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    new Task().execute();

}

@Override
   public void onDestroy() {
    super.onDestroy();
    flag = false;   
    if (serverSocket != null) {
        try {
            serverSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    stopSelf();
    Log.d("Server Stoped", "Listener Serverice is Stoped");
    // Toast.makeText(this, "Listener Destroyed", Toast.LENGTH_LONG).sho
   }
    private class Task extends AsyncTask <Void, String, String> {
        @Override
        protected String doInBackground(Void... params) {    
        try {
            serverSocket = new ServerSocket(portNo);
            serverSocket.setSoTimeout(0);
            while (flag) {
                try {
                    Socket clientSocket = serverSocket.accept();
                    BufferedReader inputReader = new BufferedReader(
                            new InputStreamReader(
                                    clientSocket.getInputStream()));
                    System.out.println("Client said :"
                            + inputReader.readLine());
                    message = inputReader.readLine();
                    Log.d("NETWORK-RECEIVE", "Message!:" + message);
                    publishProgress(message);


                    clientSocket.close();

                } catch (SocketTimeoutException e) {
                    e.printStackTrace();
                }
            }

        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return message;
    }
        @Override
        protected void onProgressUpdate(String... values) {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);
            Intent i = new Intent();
            i.setClass(getApplicationContext(), MainActivity.class);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED + WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON + WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);                                           
            startActivity(i);
            messageSend(message);
        }



    }
     protected void messageSend(String values) {               
            Log.d("AFTER", values);
            Intent intent = new Intent();
            intent.setAction(MY_ACTION);
            intent.putExtra("message", values);               
            sendBroadcast(intent);             
        }


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    Log.d("Server Startd","Listener Serverice is running");
    //Toast.makeText(getApplicationContext(),"Service Started", Toast.LENGTH_LONG).show();
    return super.onStartCommand(intent, flags, startId);
}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

}

My logcate is also here...

            09-19 12:51:07.229: D/Server Stoped(17878): Listener Serverice is Stoped
            09-19 12:51:07.229: W/System.err(17878): java.net.SocketException: Socket closed
            09-19 12:51:07.239: W/System.err(17878):    at libcore.io.Posix.accept(Native Method)
            09-19 12:51:07.239: W/System.err(17878):    at libcore.io.BlockGuardOs.accept(BlockGuardOs.java:55)
            09-19 12:51:07.239: W/System.err(17878):    at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:98)
            09-19 12:51:07.239: W/System.err(17878):    at java.net.ServerSocket.implAccept(ServerSocket.java:202)
            09-19 12:51:07.239: W/System.err(17878):    at java.net.ServerSocket.accept(ServerSocket.java:127)
            09-19 12:51:07.239: W/System.err(17878):    at com.vigosol.tcplistener.ListenerService$Task.doInBackground(ListenerService.java:88)
            09-19 12:51:07.239: W/System.err(17878):    at com.vigosol.tcplistener.ListenerService$Task.doInBackground(ListenerService.java:1)
            09-19 12:51:07.239: W/System.err(17878):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
            09-19 12:51:07.239: W/System.err(17878):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
            09-19 12:51:07.249: W/System.err(17878):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
            09-19 12:51:07.249: W/System.err(17878):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
            09-19 12:51:07.249: W/System.err(17878):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
            09-19 12:51:07.249: W/System.err(17878):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
            09-19 1

can some help me here?Any body can tell me what am i missing here in code?

Nadeem Yousaf
  • 563
  • 10
  • 31

2 Answers2

0

You've closed the ServerSocket while it was blocked in accept().

NB a zero timeout is infinite and will never cause a SocketTimeoutEzception.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

First of all is better to start your AsyncTask on onStartCommand() and as second take care on OnDestroy method.

It would be better to use an IntentService and manage your task on onHandleIntent(), is more simple if you need to manage a single thread task.

BTW: by Android Documentations:

Should you use a service or a thread? A service is simply a component that can run in the background even when the user is not interacting with your application. Thus, you should create a service only if that is what you need. If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service. For example, if you want to play some music, but only while your activity is running, you might create a thread in onCreate(), start running it in onStart(), then stop it in onStop(). Also consider using AsyncTask or HandlerThread, instead of the traditional Thread class. See the Processes and Threading document for more information about threads. Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.

Ciro Rizzo
  • 492
  • 4
  • 8