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(); } } }
public LocalSocketSessionInputBuffer(LocalSocket socket, int bufferSize, HttpParams params) throws IOException { if (HttpConnectionParams.isStaleCheckingEnabled(params)) { throw new UnsupportedOperationException( "Stale connection checking should not be used for local sockets"); } init(socket.getInputStream(), bufferSize, params); }
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(","))); }
private void passFileDescriptor(LocalSocket fdSocket, FileDescriptor tunFD) throws Exception { OutputStream outputStream = fdSocket.getOutputStream(); InputStream inputStream = fdSocket.getInputStream(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream), 1); String request = reader.readLine(); String[] parts = request.split(","); LogUtils.i("current open tcp sockets: " + tcpSockets.size()); LogUtils.i("current open udp sockets: " + udpSockets.size()); if ("TUN".equals(parts[0])) { fdSocket.setFileDescriptorsForSend(new FileDescriptor[] {tunFD}); outputStream.write('*'); } else if ("OPEN UDP".equals(parts[0])) { String socketId = parts[1]; passUdpFileDescriptor(fdSocket, outputStream, socketId); } else if ("OPEN TCP".equals(parts[0])) { String socketId = parts[1]; String dstIp = parts[2]; int dstPort = Integer.parseInt(parts[3]); int connectTimeout = Integer.parseInt(parts[4]); passTcpFileDescriptor(fdSocket, outputStream, socketId, dstIp, dstPort, connectTimeout); } else if ("CLOSE UDP".equals(parts[0])) { String socketId = parts[1]; DatagramSocket sock = udpSockets.get(socketId); if (sock != null) { udpSockets.remove(socketId); sock.close(); } } else if ("CLOSE TCP".equals(parts[0])) { String socketId = parts[1]; Socket sock = tcpSockets.get(socketId); if (sock != null) { tcpSockets.remove(socketId); sock.close(); } } else { throw new UnsupportedOperationException("fdsock unable to handle: " + request); } } finally { try { inputStream.close(); } catch (Exception e) { LogUtils.e("failed to close input stream", e); } try { outputStream.close(); } catch (Exception e) { LogUtils.e("failed to close output stream", e); } fdSocket.close(); } }
public void listen() { try { LocalServerSocket server = new LocalServerSocket(SOCKET_ADDRESS); LocalSocket receiver = server.accept(); if (receiver != null) { InputStream input = receiver.getInputStream(); byte[] buffer = new byte[1024]; // simply for java.util.ArrayList boolean rec = true; while (rec) { int read = input.read(buffer); if (read == -1) { rec = false; Log.e(TAG, "-1 read in socket"); break; } if (!isRecording) rec = false; if (!headerfound) { int i = ByteArrayFinder.find(buffer, pattern); if (i != -1) { headerfound = true; handleData(tmpch, header); handleData(tmpch, pattern); try { tmp = new byte[read - (i + pattern.length)]; System.arraycopy(buffer, i + pattern.length, tmp, 0, read - (i + pattern.length)); handleData(tmpch, tmp); Log.i(TAG, "Paquet: " + count); count++; } catch (Exception e) { } } } else { tmp = new byte[read]; System.arraycopy(buffer, 0, tmp, 0, read); handleData(tmpch, tmp); Log.i(TAG, "Paquet: " + count); count++; } // out.write(buffer, 0, readed); } headerfound = false; } } catch (IOException e) { Log.e(getClass().getName(), e.getMessage()); } }
/** * Constructs instance from connected socket. * * @param socket non-null; connected socket * @throws IOException */ ZygoteConnection(LocalSocket socket) throws IOException { mSocket = socket; mSocketOutStream = new DataOutputStream(socket.getOutputStream()); mSocketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()), 256); mSocket.setSoTimeout(CONNECTION_TIMEOUT_MILLIS); try { peer = mSocket.getPeerCredentials(); } catch (IOException ex) { Log.e(TAG, "Cannot read peer credentials", ex); throw ex; } }
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(); } }
public void start() throws IllegalStateException { super.start(); try { if (mode == MODE_STREAMING) { // receiver.getInputStream contains the data from the camera // the packetizer encapsulates this stream in an RTP stream and send it over the network packetizer.setInputStream(receiver.getInputStream()); packetizer.start(); } streaming = true; } catch (IOException e) { super.stop(); throw new IllegalStateException("Something happened with the local sockets :/ Start failed"); } catch (NullPointerException e) { super.stop(); throw new IllegalStateException( "setPacketizer() should be called before start(). Start failed"); } }
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; }
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(); } }
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; }
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); } } }
@Override public void run() { Log.i(TAG, "Connection started"); MessageWriter writer = null; MessageRouter router = null; try { MessageReader reader = new MessageReader(socket.getInputStream()); writer = new MessageWriter(socket.getOutputStream()); writers.add(writer); router = new MessageRouter(writer); router.register(Wire.MessageType.DO_IDENTIFY, new DoIdentifyResponder(getBaseContext())); router.register( Wire.MessageType.DO_ADD_ACCOUNT_MENU, new DoAddAccountMenuResponder(getBaseContext())); router.register( Wire.MessageType.DO_REMOVE_ACCOUNT, new DoRemoveAccountResponder(getBaseContext())); router.register( Wire.MessageType.GET_ACCOUNTS, new GetAccountsResponder(getBaseContext())); router.register( Wire.MessageType.GET_BROWSERS, new GetBrowsersResponder(getBaseContext())); router.register( Wire.MessageType.GET_CLIPBOARD, new GetClipboardResponder(getBaseContext())); router.register(Wire.MessageType.GET_DISPLAY, new GetDisplayResponder(getBaseContext())); router.register( Wire.MessageType.GET_PROPERTIES, new GetPropertiesResponder(getBaseContext())); router.register( Wire.MessageType.GET_RINGER_MODE, new GetRingerModeResponder(getBaseContext())); router.register( Wire.MessageType.GET_SD_STATUS, new GetSdStatusResponder(getBaseContext())); router.register(Wire.MessageType.GET_VERSION, new GetVersionResponder(getBaseContext())); router.register( Wire.MessageType.GET_WIFI_STATUS, new GetWifiStatusResponder(getBaseContext())); router.register( Wire.MessageType.SET_CLIPBOARD, new SetClipboardResponder(getBaseContext())); router.register( Wire.MessageType.SET_KEYGUARD_STATE, new SetKeyguardStateResponder(getBaseContext())); router.register( Wire.MessageType.SET_RINGER_MODE, new SetRingerModeResponder(getBaseContext())); router.register( Wire.MessageType.SET_WAKE_LOCK, new SetWakeLockResponder(getBaseContext())); router.register( Wire.MessageType.SET_WIFI_ENABLED, new SetWifiEnabledResponder(getBaseContext())); router.register( Wire.MessageType.SET_MASTER_MUTE, new SetMasterMuteResponder(getBaseContext())); for (AbstractMonitor monitor : monitors) { monitor.peek(writer); } while (!isInterrupted()) { Wire.Envelope envelope = reader.read(); if (envelope == null) { break; } router.route(envelope); } } catch (InvalidProtocolBufferException e) { Log.e(TAG, e.getMessage()); e.printStackTrace(); } catch (IOException e) { } catch (Exception e) { e.printStackTrace(); } finally { Log.i(TAG, "Connection stopping"); writers.remove(writer); if (router != null) { router.cleanup(); } try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
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 } }
@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; } } } } }