Skip to main content
Version: 1.0.0

Create connection

TCPSocket

Direct Socket API is a new Web API that provides TCP and UDP sockets. The TCPSocket class from this API can be used to create a TCP connection to an Android device.

As of September 2024, it's still not clear how Direct Socket API will be implemented. The current proposal requires the Web app to be bundled and signed by the developer, then manually installed by users. This is not a practical solution for general Web apps.

AdbDaemonDirectSocketsDevice

The following code implements an AdbDaemonDevice using a TCPSocket:

This code is based on Custom connection.

import type { AdbDaemonDevice } from "@yume-chan/adb";
import { AdbPacket, AdbPacketSerializeStream } from "@yume-chan/adb";
import {
StructDeserializeStream,
MaybeConsumable,
WrapReadableStream,
WrapWritableStream,
} from "@yume-chan/stream-extra";

export interface AdbDaemonDirectSocketDeviceOptions {
host: string;
port?: number;
name?: string;
unref?: boolean;
}

export class AdbDaemonDirectSocketsDevice implements AdbDaemonDevice {
static isSupported(): boolean {
return true;
}

#options: AdbDaemonDirectSocketDeviceOptions;

readonly serial: string;

get host(): string {
return this.#options.host;
}

readonly port: number;

get name(): string | undefined {
return this.#options.name;
}

constructor(options: AdbDaemonDirectSocketDeviceOptions) {
this.#options = options;
this.port = options.port ?? 5555;
this.serial = `${this.host}:${this.port}`;
}

async connect() {
const socket = new TCPSocket(this.host, this.port, {
noDelay: true,
unref: this.#options.unref,
});
const { readable, writable } = await socket.opened;

return {
readable: new WrapReadableStream(readable).pipeThrough(
new StructDeserializeStream(AdbPacket),
),
writable: new WrapWritableStream(writable)
.bePipedThroughFrom(new MaybeConsumable.UnwrapStream())
.bePipedThroughFrom(new AdbPacketSerializeStream()),
};
}
}

Usage

The following code creates a connection:

import type { ReadableWritablePair } from "@yume-chan/stream-extra";

const device: AdbDaemonDirectSocketsDevice = new AdbDaemonDirectSocketsDevice({
host: "192.168.50.30",
port: 5555,
});

const connection: ReadableWritablePair<
AdbPacketData,
Consumable<AdbPacketInit>
> = await device.connect();