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