Home | History | Annotate | Download | only in discovery
      1 
      2 package com.example.android.wifidirect.discovery;
      3 
      4 import android.os.Handler;
      5 import android.util.Log;
      6 
      7 import java.io.IOException;
      8 import java.net.ServerSocket;
      9 import java.util.concurrent.LinkedBlockingQueue;
     10 import java.util.concurrent.ThreadPoolExecutor;
     11 import java.util.concurrent.TimeUnit;
     12 
     13 /**
     14  * The implementation of a ServerSocket handler. This is used by the wifi p2p
     15  * group owner.
     16  */
     17 public class GroupOwnerSocketHandler extends Thread {
     18 
     19     ServerSocket socket = null;
     20     private final int THREAD_COUNT = 10;
     21     private Handler handler;
     22     private static final String TAG = "GroupOwnerSocketHandler";
     23 
     24     public GroupOwnerSocketHandler(Handler handler) throws IOException {
     25         try {
     26             socket = new ServerSocket(4545);
     27             this.handler = handler;
     28             Log.d("GroupOwnerSocketHandler", "Socket Started");
     29         } catch (IOException e) {
     30             e.printStackTrace();
     31             pool.shutdownNow();
     32             throw e;
     33         }
     34 
     35     }
     36 
     37     /**
     38      * A ThreadPool for client sockets.
     39      */
     40     private final ThreadPoolExecutor pool = new ThreadPoolExecutor(
     41             THREAD_COUNT, THREAD_COUNT, 10, TimeUnit.SECONDS,
     42             new LinkedBlockingQueue<Runnable>());
     43 
     44     @Override
     45     public void run() {
     46         while (true) {
     47             try {
     48                 // A blocking operation. Initiate a ChatManager instance when
     49                 // there is a new connection
     50                 pool.execute(new ChatManager(socket.accept(), handler));
     51                 Log.d(TAG, "Launching the I/O handler");
     52 
     53             } catch (IOException e) {
     54                 try {
     55                     if (socket != null && !socket.isClosed())
     56                         socket.close();
     57                 } catch (IOException ioe) {
     58 
     59                 }
     60                 e.printStackTrace();
     61                 pool.shutdownNow();
     62                 break;
     63             }
     64         }
     65     }
     66 
     67 }
     68