DroidConnection.java 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package org.las2mile.scrcpy;
  2. import java.io.Closeable;
  3. import java.io.EOFException;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import java.net.ServerSocket;
  8. import java.net.Socket;
  9. import java.net.InetAddress;
  10. import android.os.Build;
  11. import java.net.Inet4Address;
  12. import java.net.InetAddress;
  13. import java.net.InetSocketAddress;
  14. public final class DroidConnection implements Closeable {
  15. private static Socket socket = null;
  16. private OutputStream outputStream;
  17. private InputStream inputStream;
  18. private DroidConnection(Socket socket) throws IOException {
  19. this.socket = socket;
  20. inputStream = socket.getInputStream();
  21. outputStream = socket.getOutputStream();
  22. }
  23. private static Socket listenAndAccept() throws IOException {
  24. //只允许连接公司的设备
  25. Ln.d("The device start listenAndAccept");
  26. ServerSocket serverSocket = new ServerSocket();
  27. serverSocket.bind(new InetSocketAddress("192.168.43.1",7007));
  28. InetAddress serverIP = serverSocket.getInetAddress();
  29. String deviceIP = serverIP.getHostAddress();
  30. boolean isBound = serverSocket.isBound();
  31. Ln.d("The device isBound " +isBound);
  32. if (!"192.168.43.1".equals(deviceIP)) {
  33. Ln.d("The device is not produced");
  34. serverSocket.close();
  35. System.exit(0);
  36. return null;
  37. }
  38. Socket sock = null;
  39. try {
  40. sock = serverSocket.accept();
  41. } finally {
  42. serverSocket.close();
  43. }
  44. return sock;
  45. }
  46. public static DroidConnection open(String ip) throws IOException {
  47. socket = listenAndAccept();
  48. DroidConnection connection = null;
  49. if (socket.getInetAddress().toString().equals(ip)) {
  50. connection = new DroidConnection(socket);
  51. }
  52. return connection;
  53. }
  54. public void close() throws IOException {
  55. socket.shutdownInput();
  56. socket.shutdownOutput();
  57. socket.close();
  58. }
  59. public OutputStream getOutputStream() {
  60. return outputStream;
  61. }
  62. public int[] NewreceiveControlEvent() throws IOException {
  63. byte[] buf = new byte[16];
  64. int n = inputStream.read(buf, 0, 16);
  65. if (n == -1) {
  66. throw new EOFException("Event controller socket closed");
  67. }
  68. final int[] array = new int[buf.length / 4];
  69. for (int i = 0; i < array.length; i++)
  70. array[i] = (((int) (buf[i * 4]) << 24) & 0xFF000000) |
  71. (((int) (buf[i * 4 + 1]) << 16) & 0xFF0000) |
  72. (((int) (buf[i * 4 + 2]) << 8) & 0xFF00) |
  73. ((int) (buf[i * 4 + 3]) & 0xFF);
  74. return array;
  75. }
  76. }