コード例 #1
0
ファイル: ShellPhone.java プロジェクト: gv1/ShellPhone
 public void run() {
   ls = new LocalSocket();
   lsa = new LocalSocketAddress("/data/local/tmp/ShellPhoneSocket");
   try {
     ls.bind(lsa);
     ls.connect(lsa);
   } catch (IOException e) {
     e.printStackTrace();
   }
   while (!Thread.currentThread().isInterrupted()) {
     try {
       BufferedReader in = new BufferedReader(new InputStreamReader(ls.getInputStream()));
       while ((line = in.readLine()) != null) {
         handler.post(
             new Runnable() {
               @Override
               public void run() {
                 call(line);
                 // update
               }
             });
       }
       break;
     } catch (Exception e) {
       handler.post(
           new Runnable() {
             @Override
             public void run() {
               // interrupted connection
             }
           });
       e.printStackTrace();
     }
   }
 }
コード例 #2
0
ファイル: LauncherActivity.java プロジェクト: 0x4139/androrat
  public void constructorVideo() {
    // ctx = c;
    // this.channel = chan;

    th =
        new Thread(
            new Runnable() {

              public void run() {
                listen();
              }
            });
    th.start();

    try {
      Thread.sleep(1000);
    } catch (Exception e) {
    }

    ls = new LocalSocket();
    try {
      ls.connect(new LocalSocketAddress(SOCKET_ADDRESS));
    } catch (IOException e) {
      // stop();
    }
    camera = Camera.open();
  }
コード例 #3
0
 private void createSockets() throws IOException {
   receiver = new LocalSocket();
   receiver.connect(new LocalSocketAddress("net.majorkernelpanic.librtp-" + socketId));
   receiver.setReceiveBufferSize(500000);
   sender = lss.accept();
   sender.setSendBufferSize(500000);
 }
コード例 #4
0
    static ZygoteState connect(String socketAddress, int tries) throws ZygoteStartFailedEx {
      LocalSocket zygoteSocket = null;
      DataInputStream zygoteInputStream = null;
      BufferedWriter zygoteWriter = null;

      /*
       * See bug #811181: Sometimes runtime can make it up before zygote.
       * Really, we'd like to do something better to avoid this condition,
       * but for now just wait a bit...
       *
       * TODO: This bug was filed in 2007. Get rid of this code. The zygote
       * forks the system_server so it shouldn't be possible for the zygote
       * socket to be brought up after the system_server is.
       */
      for (int i = 0; i < tries; i++) {
        if (i > 0) {
          try {
            Log.i(LOG_TAG, "Zygote not up yet, sleeping...");
            Thread.sleep(ZYGOTE_RETRY_MILLIS);
          } catch (InterruptedException ex) {
            throw new ZygoteStartFailedEx(ex);
          }
        }

        try {
          zygoteSocket = new LocalSocket();
          zygoteSocket.connect(
              new LocalSocketAddress(socketAddress, LocalSocketAddress.Namespace.RESERVED));

          zygoteInputStream = new DataInputStream(zygoteSocket.getInputStream());

          zygoteWriter =
              new BufferedWriter(new OutputStreamWriter(zygoteSocket.getOutputStream()), 256);
          break;
        } catch (IOException ex) {
          if (zygoteSocket != null) {
            try {
              zygoteSocket.close();
            } catch (IOException ex2) {
              Log.e(LOG_TAG, "I/O exception on close after exception", ex2);
            }
          }

          zygoteSocket = null;
        }
      }

      if (zygoteSocket == null) {
        throw new ZygoteStartFailedEx("connect failed");
      }

      String abiListString = getAbiList(zygoteWriter, zygoteInputStream);
      Log.i("Zygote", "Process: zygote socket opened, supported ABIS: " + abiListString);

      return new ZygoteState(
          zygoteSocket, zygoteInputStream, zygoteWriter, Arrays.asList(abiListString.split(",")));
    }
コード例 #5
0
  public void testAccessors() throws IOException {
    LocalSocket socket = new LocalSocket();
    LocalSocketAddress addr = new LocalSocketAddress("secondary");

    assertFalse(socket.isBound());
    socket.bind(addr);
    assertTrue(socket.isBound());
    assertEquals(addr, socket.getLocalSocketAddress());

    String str = socket.toString();
    assertTrue(str.contains("impl:android.net.LocalSocketImpl"));

    socket.setReceiveBufferSize(1999);
    assertEquals(1999 << 1, socket.getReceiveBufferSize());

    socket.setSendBufferSize(3998);
    assertEquals(3998 << 1, socket.getSendBufferSize());

    // Timeout is not support at present, so set is ignored
    socket.setSoTimeout(1996);
    assertEquals(0, socket.getSoTimeout());

    try {
      socket.getRemoteSocketAddress();
      fail("testLocalSocketSecondary shouldn't come to here");
    } catch (UnsupportedOperationException e) {
      // expected
    }

    try {
      socket.isClosed();
      fail("testLocalSocketSecondary shouldn't come to here");
    } catch (UnsupportedOperationException e) {
      // expected
    }

    try {
      socket.isInputShutdown();
      fail("testLocalSocketSecondary shouldn't come to here");
    } catch (UnsupportedOperationException e) {
      // expected
    }

    try {
      socket.isOutputShutdown();
      fail("testLocalSocketSecondary shouldn't come to here");
    } catch (UnsupportedOperationException e) {
      // expected
    }

    try {
      socket.connect(addr, 2005);
      fail("testLocalSocketSecondary shouldn't come to here");
    } catch (UnsupportedOperationException e) {
      // expected
    }
  }
コード例 #6
0
ファイル: SocketUtils.java プロジェクト: ht101996/VideoChat
  public static void initLocalSocket() {
    Log.i(Global.TAG, " --------------initLocalSocket start!");
    try {
      if (videoReceiverLocalSocket == null) {

        videoLocalServerSocket = new LocalServerSocket("VideoCamera");

        videoReceiverLocalSocket = new LocalSocket();
        videoReceiverLocalSocket.connect(new LocalSocketAddress("VideoCamera"));
        videoReceiverLocalSocket.setReceiveBufferSize(20480); // 500000
        videoReceiverLocalSocket.setSendBufferSize(20480); //

        videoSenderLocalSocket = videoLocalServerSocket.accept();
        videoSenderLocalSocket.setReceiveBufferSize(20480);
        videoSenderLocalSocket.setSendBufferSize(20480);
      }
      // audio
      if (audioLocalServerSocket == null) {
        audioLocalServerSocket = new LocalServerSocket("AudioCamera");

        audioReceiverLocalSocket = new LocalSocket();
        audioReceiverLocalSocket.connect(new LocalSocketAddress("AudioCamera"));
        audioReceiverLocalSocket.setReceiveBufferSize(20480);
        audioReceiverLocalSocket.setSendBufferSize(20480); //

        audioSenderLocalSocket = audioLocalServerSocket.accept();
        audioSenderLocalSocket.setReceiveBufferSize(20480);
        audioSenderLocalSocket.setSendBufferSize(20480);
      }

      Log.i(
          Global.TAG, " --------------initLocalSocket ended!receiver==" + videoReceiverLocalSocket);
      Log.i(Global.TAG, " --------------initLocalSocket ended!sender==" + videoSenderLocalSocket);
    } catch (IOException e) {
      e.printStackTrace();
      releaseLocalSocket();
    }
    Log.i(Global.TAG, " --------------initLocalSocket end!");
  }
コード例 #7
0
  public void init() {
    try {
      localLoop = new LocalServerSocket("videoserver");
      localReceiver = new LocalSocket();
      localReceiver.connect(localLoop.getLocalSocketAddress());
      localReceiver.setReceiveBufferSize(LOCAL_BUFF_SIZE);
      localReceiver.setSendBufferSize(LOCAL_BUFF_SIZE);

      localSender = localLoop.accept();
      localSender.setReceiveBufferSize(LOCAL_BUFF_SIZE);
      localSender.setSendBufferSize(LOCAL_BUFF_SIZE);

      Log.d(LOG_TAG, "Done: init()");
    } catch (IOException e) {
      Log.e(LOG_TAG, "Error in initializing local socket: " + e);
    }
  }
コード例 #8
0
  private void startLocalClient(String name, String message) throws Exception {
    // Construct a local socket
    LocalSocket clientSocket = new LocalSocket();
    try {
      // Set the socket namespace
      LocalSocketAddress.Namespace namespace;
      if (isFilesystemSocket(name)) {
        namespace = LocalSocketAddress.Namespace.FILESYSTEM;
      } else {
        namespace = LocalSocketAddress.Namespace.ABSTRACT;
      }

      // Construct local socket address
      LocalSocketAddress address = new LocalSocketAddress(name, namespace);

      // Connect to local socket
      logMessage("Connecting to " + name);
      clientSocket.connect(address);
      logMessage("Connected.");
      // Get message as bytes
      byte[] messageBytes = message.getBytes();
      // Send message bytes to the socket
      logMessage("Sending to the socket...");
      OutputStream outputStream = clientSocket.getOutputStream();
      outputStream.write(messageBytes);
      logMessage(String.format("Sent %d bytes: %s", messageBytes.length, message));

      // Receive the message back from the socket
      logMessage("Receiving from the socket...");
      InputStream inputStream = clientSocket.getInputStream();
      int readSize = inputStream.read(messageBytes);

      String receivedMessage = new String(messageBytes, 0, readSize);
      logMessage(String.format("Received %d bytes: %s", readSize, receivedMessage));

      // Close streams
      outputStream.close();
      inputStream.close();

    } finally {
      // Close the local socket
      clientSocket.close();
    }
  }
コード例 #9
0
  private boolean connect() {
    if (mSocket != null) {
      return true;
    }
    Slog.i(TAG, "connecting...");
    try {
      mSocket = new LocalSocket();

      LocalSocketAddress address =
          new LocalSocketAddress("installd", LocalSocketAddress.Namespace.RESERVED);

      mSocket.connect(address);

      mIn = mSocket.getInputStream();
      mOut = mSocket.getOutputStream();
    } catch (IOException ex) {
      disconnect();
      return false;
    }
    return true;
  }
コード例 #10
0
  private void listenToSocket() throws IOException {
    try {
      byte[] buffer = new byte[BUFFER_SIZE];
      LocalSocketAddress address =
          new LocalSocketAddress(ADBD_SOCKET, LocalSocketAddress.Namespace.RESERVED);
      InputStream inputStream = null;

      mSocket = new LocalSocket();
      mSocket.connect(address);

      mOutputStream = mSocket.getOutputStream();
      inputStream = mSocket.getInputStream();

      while (true) {
        int count = inputStream.read(buffer);
        if (count < 0) {
          Slog.e(TAG, "got " + count + " reading");
          break;
        }

        if (buffer[0] == 'P' && buffer[1] == 'K') {
          String key = new String(Arrays.copyOfRange(buffer, 2, count));
          Slog.d(TAG, "Received public key: " + key);
          Message msg = mHandler.obtainMessage(UsbDebuggingHandler.MESSAGE_ADB_CONFIRM);
          msg.obj = key;
          mHandler.sendMessage(msg);
        } else {
          Slog.e(TAG, "Wrong message: " + (new String(Arrays.copyOfRange(buffer, 0, 2))));
          break;
        }
      }
    } catch (IOException ex) {
      Slog.e(TAG, "Communication error: ", ex);
      throw ex;
    } finally {
      closeSocket();
    }
  }
コード例 #11
0
    public Boolean setup() {
      // if work as wave data generator, do not need the local data server
      if (mIsWorkAsGenerator) return true;

      try {
        if (mLocalSocket == null) {
          mLocalSocket = new LocalSocket();
        }

        if (mSocketAddress == null) {
          mSocketAddress =
              new LocalSocketAddress(
                  DATA_SERVER_SOCKET_NAME, LocalSocketAddress.Namespace.ABSTRACT);
        }
        mLocalSocket.connect(mSocketAddress);

      } catch (IOException ex) {
        Log.d(TAG, "Create local socket failed", ex);
        mLocalSocket = null;
      }

      if (mLocalSocket == null) return false;

      try {
        mLocalInputStream = mLocalSocket.getInputStream();
        mLocalOutputStream = mLocalSocket.getOutputStream();
      } catch (IOException e) {
        mLocalSocket = null;
        mLocalInputStream = null;
        mLocalOutputStream = null;
        Log.e(TAG, "temp sockets not created", e);
      }

      if (mLocalSocket == null) return false;

      return true;
    }
コード例 #12
0
  private void listenToSocket() throws IOException {
    LocalSocket socket = null;

    try {
      socket = new LocalSocket();
      LocalSocketAddress address =
          new LocalSocketAddress(mSocket, LocalSocketAddress.Namespace.RESERVED);

      socket.connect(address);

      InputStream inputStream = socket.getInputStream();
      mOutputStream = socket.getOutputStream();

      mCallbacks.onDaemonConnected();

      byte[] buffer = new byte[BUFFER_SIZE];
      int start = 0;

      while (true) {
        int count = inputStream.read(buffer, start, BUFFER_SIZE - start);
        if (count < 0) break;

        for (int i = 0; i < count; i++) {
          if (buffer[i] == 0) {
            String event = new String(buffer, start, i - start);
            if (LOCAL_LOGD) Slog.d(TAG, String.format("RCV <- {%s}", event));

            String[] tokens = event.split(" ");
            try {
              int code = Integer.parseInt(tokens[0]);

              if (code >= ResponseCode.UnsolicitedInformational) {
                try {
                  if (!mCallbacks.onEvent(code, event, tokens)) {
                    Slog.w(TAG, String.format("Unhandled event (%s)", event));
                  }
                } catch (Exception ex) {
                  Slog.e(TAG, String.format("Error handling '%s'", event), ex);
                }
              } else {
                try {
                  mResponseQueue.put(event);
                } catch (InterruptedException ex) {
                  Slog.e(TAG, "Failed to put response onto queue", ex);
                }
              }
            } catch (NumberFormatException nfe) {
              Slog.w(TAG, String.format("Bad msg (%s)", event));
            }
            start = i + 1;
          }
        }
        if (start != count) {
          final int remaining = BUFFER_SIZE - start;
          System.arraycopy(buffer, start, buffer, 0, remaining);
          start = remaining;
        } else {
          start = 0;
        }
      }
    } catch (IOException ex) {
      Slog.e(TAG, "Communications error", ex);
      throw ex;
    } finally {
      synchronized (this) {
        if (mOutputStream != null) {
          try {
            mOutputStream.close();
          } catch (IOException e) {
            Slog.w(TAG, "Failed closing output stream", e);
          }
          mOutputStream = null;
        }
      }

      try {
        if (socket != null) {
          socket.close();
        }
      } catch (IOException ex) {
        Slog.w(TAG, "Failed closing socket", ex);
      }
    }
  }
コード例 #13
0
  public void testLocalConnections() throws IOException {
    // create client and server socket
    LocalServerSocket localServerSocket = new LocalServerSocket(mSockAddr);
    LocalSocket clientSocket = new LocalSocket();

    // establish connection between client and server
    LocalSocketAddress locSockAddr = new LocalSocketAddress(mSockAddr);
    assertFalse(clientSocket.isConnected());
    clientSocket.connect(locSockAddr);
    assertTrue(clientSocket.isConnected());
    LocalSocket serverSocket = localServerSocket.accept();

    Credentials credent = clientSocket.getPeerCredentials();
    assertTrue(0 != credent.getPid());

    // send data from client to server
    OutputStream clientOutStream = clientSocket.getOutputStream();
    clientOutStream.write(12);
    InputStream serverInStream = serverSocket.getInputStream();
    assertEquals(12, serverInStream.read());

    // send data from server to client
    OutputStream serverOutStream = serverSocket.getOutputStream();
    serverOutStream.write(3);
    InputStream clientInStream = clientSocket.getInputStream();
    assertEquals(3, clientInStream.read());

    // Test sending and receiving file descriptors
    clientSocket.setFileDescriptorsForSend(new FileDescriptor[] {FileDescriptor.in});
    clientOutStream.write(32);
    assertEquals(32, serverInStream.read());

    FileDescriptor[] out = serverSocket.getAncillaryFileDescriptors();
    assertEquals(1, out.length);
    FileDescriptor fd = clientSocket.getFileDescriptor();
    assertTrue(fd.valid());

    // shutdown input stream of client
    clientSocket.shutdownInput();
    assertEquals(-1, clientInStream.read());

    // shutdown output stream of client
    clientSocket.shutdownOutput();
    try {
      clientOutStream.write(10);
      fail("testLocalSocket shouldn't come to here");
    } catch (IOException e) {
      // expected
    }

    // shutdown input stream of server
    serverSocket.shutdownInput();
    assertEquals(-1, serverInStream.read());

    // shutdown output stream of server
    serverSocket.shutdownOutput();
    try {
      serverOutStream.write(10);
      fail("testLocalSocket shouldn't come to here");
    } catch (IOException e) {
      // expected
    }

    // close client socket
    clientSocket.close();
    try {
      clientInStream.read();
      fail("testLocalSocket shouldn't come to here");
    } catch (IOException e) {
      // expected
    }

    // close server socket
    serverSocket.close();
    try {
      serverInStream.read();
      fail("testLocalSocket shouldn't come to here");
    } catch (IOException e) {
      // expected
    }
  }
コード例 #14
0
  @Override
  public void onMessage(final DataChannel.Buffer inbuf) {

    ByteBuffer data = inbuf.data;
    if (inbuf.binary) {
      if (bStart) {
        try {
          if (writableByteChannel != null) {
            writableByteChannel.write(data);
          } else {
            Log.e(TAG, "writeableByteChannel is null");
          }
        } catch (Exception e) {
          Log.d(TAG, "os write fail:" + e);
        }
      }
    } else {
      int size = data.remaining();
      byte[] bytes = new byte[size];
      data.get(bytes);

      String command = new String(bytes);
      String[] cmd_split = command.split(":");
      String msgType = cmd_split[0];
      String msgKey = cmd_split[1];

      if (isAudioMessage(msgType)) {
        String audioMsg = "Get Audio: ";
        Log.d(TAG, audioMsg + command);

        if (msgKey.equalsIgnoreCase("SET")) {

          if (cmd_split[2].equalsIgnoreCase("OV")) {
            sourceType = SourceType.OV;
            setting = "";
          } else if (cmd_split[2].equalsIgnoreCase("RTSP")) {
            sourceType = SourceType.RTSP;
            // collect parameter after SET:
            // ex: 1. AUDIO:SET:RTSP:AAC:1:8000:1588:.....
            // ex: 2. AUDIO:SET:RTSP:mG711:1:....
            // ex: 3. AUDIO:SET:RTSP:aG711:1:....
            setting = command.substring(10, command.length());
            Log.d(TAG, setting);
          }
        }

        if (msgKey.equalsIgnoreCase("START")) {

          if (sourceType == SourceType.UNKNOWN) {
            Log.e(TAG, "Audio Something wrong!!");
            return;
          }

          audioMsg = audioMsg + "START";

          if (at != null) {
            at.setStop();
            at.interrupt();
            at = null;
          }

          if (nat != null) {
            nat.setStop();
            nat.interrupt();
            nat = null;
          }

          for (int jj = 0; jj < 10; jj++) {
            try {
              mSocketId = new Random().nextInt();
              mLss = new LocalServerSocket(LOCAL_ADDR + mSocketId);
              break;
            } catch (IOException e) {
              Log.e(TAG, "fail to create localserversocket :" + e);
            }
          }

          //    DECODE FLOW
          //
          //    Intermediary:                             Localsocket       MediaCodec inputBuffer
          //   MediaCodec outputBuffer
          //        Flow    : Data Channel =======> Sender ========> Receiver ==================>
          // Decoder =================> Display to surface/ Play by Audio Track
          //       Thread   : |<---Data Channel thread--->|          |<--------- Decode Thread
          // --------->|                 |<--------- Display/play Thread -------->|
          //
          mReceiver = new LocalSocket();
          try {
            mReceiver.connect(new LocalSocketAddress(LOCAL_ADDR + mSocketId));
            mReceiver.setReceiveBufferSize(100000);
            mReceiver.setSoTimeout(200);
            mSender = mLss.accept();
            mSender.setSendBufferSize(100000);
          } catch (IOException e) {
            Log.e(TAG, "fail to create mSender mReceiver :" + e);
            e.printStackTrace();
          }
          try {
            os = mSender.getOutputStream();
            writableByteChannel = Channels.newChannel(os);
            is = mReceiver.getInputStream();
          } catch (IOException e) {
            Log.e(TAG, "fail to get mSender mReceiver :" + e);
            e.printStackTrace();
          }
          bStart = true;

          if (sourceType == SourceType.OV) {
            // using self adpcm_ima decoder to decode audio
            at = new AudioThread(is);
            at.start();
          } else if (sourceType == SourceType.RTSP) {
            // using mediaCodec to decode audio
            nat = new NormalAudioThread(is, setting);
            nat.start();
          }
        }

        if (msgKey.equalsIgnoreCase("STOP")) {
          if (bStart) {
            audioMsg = audioMsg + "STOP";

            try {
              os.close();
              is.close();
              writableByteChannel.close();
              writableByteChannel = null;
              os = null;
              is = null;
            } catch (Exception e) {
              Log.e(TAG, "Close input/output stream error : " + e);
            }

            if (at != null) {
              at.setStop();
              at.interrupt();
              at = null;
            }

            if (nat != null) {
              nat.setStop();
              nat.interrupt();
              nat = null;
            }

            bStart = false;
          }
        }
      }
    }
  }