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.io.InputStream; 9 import java.io.OutputStream; 10 import java.net.Socket; 11 import java.util.Arrays; 12 13 /** 14 * Handles reading and writing of messages with socket buffers. Uses a Handler 15 * to post messages to UI thread for UI updates. 16 */ 17 public class ChatManager implements Runnable { 18 19 private Socket socket = null; 20 private Handler handler; 21 ChatManager(Socket socket, Handler handler)22 public ChatManager(Socket socket, Handler handler) { 23 this.socket = socket; 24 this.handler = handler; 25 } 26 27 private InputStream iStream; 28 private OutputStream oStream; 29 private static final String TAG = "ChatHandler"; 30 31 @Override run()32 public void run() { 33 try { 34 35 iStream = socket.getInputStream(); 36 oStream = socket.getOutputStream(); 37 byte[] buffer = new byte[1024]; 38 int bytes; 39 handler.obtainMessage(WiFiServiceDiscoveryActivity.MY_HANDLE, this) 40 .sendToTarget(); 41 42 while (true) { 43 try { 44 // Read from the InputStream 45 bytes = iStream.read(buffer); 46 if (bytes == -1) { 47 break; 48 } 49 50 // Send the obtained bytes to the UI Activity 51 Log.d(TAG, "Rec:" + Arrays.toString(buffer)); 52 handler.obtainMessage(WiFiServiceDiscoveryActivity.MESSAGE_READ, 53 bytes, -1, buffer).sendToTarget(); 54 } catch (IOException e) { 55 Log.e(TAG, "disconnected", e); 56 } 57 } 58 } catch (IOException e) { 59 e.printStackTrace(); 60 } finally { 61 try { 62 socket.close(); 63 } catch (IOException e) { 64 e.printStackTrace(); 65 } 66 } 67 } 68 write(String msg)69 public void write(String msg) { 70 byte[] buffer = msg.getBytes(); 71 Thread thread = new Thread() { 72 public void run() { 73 try { 74 oStream.write(buffer); 75 } catch (IOException e) { 76 Log.e(TAG, "Exception during write", e); 77 } 78 } 79 }; 80 thread.start(); 81 } 82 83 } 84