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.InetAddress;
9 import java.net.InetSocketAddress;
10 import java.net.Socket;
11 
12 public class ClientSocketHandler extends Thread {
13 
14     private static final String TAG = "ClientSocketHandler";
15     private Handler handler;
16     private ChatManager chat;
17     private InetAddress mAddress;
18 
ClientSocketHandler(Handler handler, InetAddress groupOwnerAddress)19     public ClientSocketHandler(Handler handler, InetAddress groupOwnerAddress) {
20         this.handler = handler;
21         this.mAddress = groupOwnerAddress;
22     }
23 
24     @Override
run()25     public void run() {
26         Socket socket = new Socket();
27         try {
28             socket.bind(null);
29             socket.connect(new InetSocketAddress(mAddress.getHostAddress(),
30                     WiFiServiceDiscoveryActivity.SERVER_PORT), 5000);
31             Log.d(TAG, "Launching the I/O handler");
32             chat = new ChatManager(socket, handler);
33             new Thread(chat).start();
34         } catch (IOException e) {
35             e.printStackTrace();
36             try {
37                 socket.close();
38             } catch (IOException e1) {
39                 e1.printStackTrace();
40             }
41             return;
42         }
43     }
44 
getChat()45     public ChatManager getChat() {
46         return chat;
47     }
48 
49 }
50