leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | package com.androidremote.companion |
| 2 | |
| 3 | import android.content.Context |
| 4 | import android.os.Handler |
| 5 | import android.os.Looper |
| 6 | import org.json.JSONObject |
| 7 | import java.io.BufferedReader |
| 8 | import java.io.InputStreamReader |
| 9 | import java.io.OutputStreamWriter |
| 10 | import java.net.InetSocketAddress |
| 11 | import java.net.Socket |
| 12 | |
| 13 | /** |
| 14 | * 데몬 로컬 연결(127.0.0.1 TCP + 토큰) 클라이언트. 받은 메시지는 메인 스레드에서 [onMessage]로, |
| 15 | * 연결 상태 변화는 [onConnected]로 알린다. 끊기면 2초마다 다시 시도한다. |
| 16 | */ |
| 17 | class DaemonClient( |
| 18 | private val context: Context, |
| 19 | private val onMessage: (JSONObject) -> Unit, |
| 20 | private val onConnected: (Boolean) -> Unit, |
| 21 | ) { |
| 22 | private val main = Handler(Looper.getMainLooper()) |
| 23 | @Volatile private var running = false |
| 24 | @Volatile private var writer: OutputStreamWriter? = null |
| 25 | private var socket: Socket? = null |
| 26 | private var thread: Thread? = null |
| 27 | |
| 28 | fun start() { |
| 29 | if (running) return |
| 30 | running = true |
| 31 | thread = Thread(::loop, "daemon-client").also { it.start() } |
| 32 | } |
| 33 | |
| 34 | fun stop() { |
| 35 | running = false |
| 36 | runCatching { socket?.close() } |
| 37 | thread?.interrupt() |
| 38 | } |
| 39 | |
| 40 | fun send(msg: JSONObject) { |
| 41 | val w = writer ?: return |
| 42 | Thread { |
| 43 | runCatching { |
| 44 | synchronized(w) { |
| 45 | w.write(msg.toString()) |
| 46 | w.write("\n") |
| 47 | w.flush() |
| 48 | } |
| 49 | } |
| 50 | }.start() |
| 51 | } |
| 52 | |
| 53 | private fun loop() { |
| 54 | var notifiedDown = false |
| 55 | while (running) { |
| 56 | try { |
| 57 | val (token, port) = DaemonEndpoint.load(context) ?: throw IllegalStateException("토큰 없음") |
| 58 | val s = Socket() |
| 59 | s.connect(InetSocketAddress("127.0.0.1", port), 1000) |
| 60 | socket = s |
| 61 | val w = OutputStreamWriter(s.outputStream, Charsets.UTF_8) |
| 62 | w.write(JSONObject().put("type", "hello").put("token", token).toString()) |
| 63 | w.write("\n") |
| 64 | w.flush() |
| 65 | writer = w |
| 66 | notifiedDown = false |
| 67 | main.post { onConnected(true) } |
| 68 | val reader = BufferedReader(InputStreamReader(s.inputStream, Charsets.UTF_8)) |
| 69 | while (running) { |
| 70 | val line = reader.readLine() ?: break |
| 71 | val msg = runCatching { JSONObject(line) }.getOrNull() ?: continue |
| 72 | main.post { onMessage(msg) } |
| 73 | } |
| 74 | } catch (e: Exception) { |
| 75 | // 데몬이 아직 실행 중이 아니다. |
| 76 | } |
| 77 | writer = null |
| 78 | runCatching { socket?.close() } |
| 79 | if (!notifiedDown) { |
| 80 | notifiedDown = true |
| 81 | main.post { onConnected(false) } |
| 82 | } |
| 83 | try { |
| 84 | Thread.sleep(2000) |
| 85 | } catch (e: InterruptedException) { |
| 86 | break |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | } |