Skip to content

Commit 66ff791

Browse files
authored
feat: add file transfer over data channels (#575)
1 parent 22ebdb5 commit 66ff791

24 files changed

Lines changed: 3451 additions & 0 deletions

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ The library provides a comprehensive set of Java classes that map to the WebRTC
1919
- **[WHIP and WHEP](https://jrtc.dev/guide/client-api#whip-and-whep)** - Publish to and play from streaming servers
2020
- **[Peer connections](https://jrtc.dev/guide/networking/peer-connection-config)** - The full native API, modeled on the W3C JavaScript API
2121
- **[Data channels](https://jrtc.dev/guide/data/data-channels)** - Reliable or unreliable peer-to-peer messaging
22+
- **[File transfer](https://jrtc.dev/guide/data/file-transfer)** - Send files over a data channel with progress, a checksum confirmed by the receiver and resume after a reconnect
2223
- **[Statistics](https://jrtc.dev/guide/monitoring/rtc-stats)** - Detailed metrics on connection quality
2324

2425
**Audio and video**

‎docs/.vitepress/sidebar.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ function sidebarGuide(): DefaultTheme.SidebarItem[] {
5454
collapsed: false,
5555
items: [
5656
{ text: 'Data Channels', link: '/data/data-channels' },
57+
{ text: 'File Transfer', link: '/data/file-transfer' },
5758
],
5859
},
5960
{

‎docs/guide/client-api.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -759,6 +759,8 @@ DataChannel positions = peer.createChannel("positions", ChannelOptions.builder()
759759

760760
`negotiatedId(int)` creates a channel both peers set up themselves with the same id, without announcing it; such a channel never shows up in `onChannel`. The [Data Channels](/guide/data/data-channels) guide explains the options in detail.
761761

762+
A completed `send` future means the data was handed to the transport, not that the remote application processed it. To send files, use `FileTransfers` from `dev.onvoid.webrtc.client.transfer`, which adds the receiver's own confirmations, a SHA-256 checksum, progress, cancelling and resume. See the [File Transfer](/guide/data/file-transfer) guide.
763+
762764
## WHIP and WHEP
763765

764766
Media servers and streaming services take streams with the WebRTC HTTP Ingestion Protocol ([WHIP](https://www.rfc-editor.org/rfc/rfc9725)) and hand them out with its egress counterpart, WHEP. Both exchange one offer and one answer over HTTP. `Whip` publishes tracks, and `Whep` receives a stream:

‎docs/guide/data/file-transfer.md‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# File Transfer
2+
3+
`dev.onvoid.webrtc.client.transfer` sends files over a [client API](/guide/client-api) data channel. It adds what a plain `send()` doesn't give you: chunking with bounded memory, progress, cancelling, a confirmation from the receiver with a SHA-256 checksum, and resuming after a reconnect.
4+
5+
```java
6+
FileTransfers files = FileTransfers.over(peer.createChannel("files"));
7+
8+
OutgoingTransfer upload = files.send(Paths.get("report.pdf"));
9+
upload.onProgress(p -> System.out.printf("%.0f%%%n", 100 * p.fraction()));
10+
upload.whenDone().thenRun(() -> System.out.println("The receiver has it"));
11+
12+
// On the other side:
13+
peer.onChannel(channel -> {
14+
if (channel.label().equals("files")) {
15+
FileTransfers.over(channel).onOffer(offer ->
16+
offer.accept(downloads.resolve(offer.safeFileName())));
17+
}
18+
});
19+
```
20+
21+
`FileTransfers` takes over the channel: nothing else may be sent on it. Files go one at a time in each direction, in the order they were sent, and both peers may send at the same time. Each side reads and writes its files and runs its handlers on a thread of its own, not on the peer's event thread. Those handlers must not block.
22+
23+
## Confirmation, not just handing data to the transport
24+
25+
The future that `DataChannel.send()` returns completes once the data has been handed to the transport. It tells you nothing about the receiver. The transfer protocol has its own confirmations:
26+
27+
- The receiver acknowledges the bytes it wrote to its file, a quarter of its window at a time. Progress on both sides counts confirmed bytes.
28+
- The sender never has more than the receiver's window unconfirmed (`TransferOptions.builder().window(bytes)`, 4 MiB by default). A slow disk therefore slows the sender down instead of filling memory. Keep the window below the receiver's `channelReceiveLimit`.
29+
- `whenDone()` completes only once the receiver has checked the SHA-256 of the whole file against the sender's and moved the file into place.
30+
31+
## Offers
32+
33+
An offer's `name()` and `size()` come from the remote peer. Don't turn the name into a path as it is, because it may contain `../` or path separators. `safeFileName()` gives you a single file name that stays in the directory you resolve it against. `reject(reason)` makes the sender's transfer fail with that reason, and the sender's next file follows. If an offer arrives before any handler is registered, it waits for the first handler.
34+
35+
The data goes to `partialFile()` next to the target, and that file replaces the target only after the checksum matched. If more data arrives than the offer announced, or more than the window allows, or the data is out of order, the receiver treats it as a protocol error: the transfer fails and the channel closes.
36+
37+
## Cancelling and failures
38+
39+
`cancel()` works on either side. It tells the remote peer, and the receiver deletes its partial file. The other side fails with a `TransferCancelledException`. Every other failure is a `TransferException`, for example a rejected offer, a checksum mismatch, a read or write error, or a protocol error.
40+
41+
## Resuming after a reconnect
42+
43+
When the channel closes, or `close()` is called, unfinished transfers fail with an exception whose `isResumable()` is true. The receiver keeps its partial file. Over a new channel, for example of a new peer after the connection has been set up again, the sender resumes the transfer:
44+
45+
```java
46+
OutgoingTransfer resumed = newFiles.resume(interrupted);
47+
```
48+
49+
The offer keeps its id. If the receiver accepts it with the same target, the transfer continues from the end of the partial file, and the checksum still covers the whole file. With `TransferOptions.builder().resumable(false)`, the receiver deletes partial files on every failure and always starts over. An application that won't resume a transfer deletes `partialFile()` itself.
50+
51+
## Wire format
52+
53+
Each frame is one binary message, big-endian, and starts with its type and the 16-byte transfer id:
54+
55+
| Frame | Type | Fields after the id |
56+
|--------|------|-----------------------------------------|
57+
| OFFER | 1 | version (u8, 1), size (u64), name (text) |
58+
| ACCEPT | 2 | offset (u64), window (u32) |
59+
| REJECT | 3 | reason (text) |
60+
| DATA | 4 | offset (u64), payload |
61+
| ACK | 5 | offset (u64) |
62+
| END | 6 | SHA-256 (32 bytes) |
63+
| DONE | 7 | |
64+
| CANCEL | 8 | failed (u8), reason (text) |
65+
66+
A text is a u16 length followed by at most 1024 bytes of UTF-8.

‎docs/guide/examples.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,22 @@ This example is the shortest way to see a complete call working, and a starting
2222
mvn exec:java -D"exec.mainClass=dev.onvoid.webrtc.examples.ClientApiExample" -D"exec.args=10"
2323
```
2424

25+
## File Transfer
26+
27+
The [`FileTransferExample`](https://github.com/devopvoid/webrtc-java/blob/master/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/FileTransferExample.java) connects two peers in one process with the [Client API](/guide/client-api), and sends a file from one to the other with [File Transfer](/guide/data/file-transfer). It needs no audio or video hardware and no server.
28+
29+
**Key features demonstrated:**
30+
- Running `FileTransfers` over a data channel on both sides
31+
- Accepting an offer under a safe file name, in a directory of the application's choice
32+
- Following the progress the receiver confirms
33+
- Waiting until the receiver checked the SHA-256 of the file and moved it into place
34+
35+
Pass a file to send, or a size in MiB for a file of random data, 20 by default:
36+
37+
```bash
38+
mvn exec:java -D"exec.mainClass=dev.onvoid.webrtc.examples.FileTransferExample" -D"exec.args=50"
39+
```
40+
2541
## PeerConnection
2642

2743
The [`PeerConnectionExample`](https://github.com/devopvoid/webrtc-java/blob/master/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/PeerConnectionExample.java) sends the camera and the microphone from one peer to another in the same process, with the [Client API](/guide/client-api), and logs the video frames and audio that arrive.

‎docs/guide/index.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ This section provides detailed guides for various features of the webrtc-java li
2727
## Data Communication
2828

2929
- [Data Channels](/guide/data/data-channels) - Sending and receiving arbitrary data between peers
30+
- [File Transfer](/guide/data/file-transfer) - Sending files with progress, confirmation, checksum and resume
3031

3132
## Networking and ICE
3233

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
/*
2+
* Copyright 2026 Alex Andres
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package dev.onvoid.webrtc.examples;
18+
19+
import java.nio.file.Files;
20+
import java.nio.file.Path;
21+
import java.nio.file.Paths;
22+
import java.util.Arrays;
23+
import java.util.Random;
24+
import java.util.concurrent.CompletableFuture;
25+
import java.util.concurrent.TimeUnit;
26+
27+
import dev.onvoid.webrtc.client.AudioMode;
28+
import dev.onvoid.webrtc.client.Peer;
29+
import dev.onvoid.webrtc.client.PeerOptions;
30+
import dev.onvoid.webrtc.client.Signaling;
31+
import dev.onvoid.webrtc.client.SignalingPair;
32+
import dev.onvoid.webrtc.client.WebRtc;
33+
import dev.onvoid.webrtc.client.transfer.FileTransfers;
34+
import dev.onvoid.webrtc.client.transfer.IncomingTransfer;
35+
import dev.onvoid.webrtc.client.transfer.OutgoingTransfer;
36+
37+
/**
38+
* Example of file transfer over a data channel ({@code dev.onvoid.webrtc.client.transfer}): two
39+
* peers in one process, one sends a file, the other saves it.
40+
* <p>
41+
* This example shows how to:
42+
* <ul>
43+
* <li>Run {@link FileTransfers} over a data channel on both sides</li>
44+
* <li>Accept an offer under a safe file name in a directory of the application's choice</li>
45+
* <li>Follow the progress the receiver confirms</li>
46+
* <li>Wait until the receiver checked the SHA-256 of the file and moved it into place</li>
47+
* </ul>
48+
* <p>
49+
* Pass a file to send, or a size in MiB for a file of random data, 20 by default:
50+
* <pre>
51+
* mvn exec:java -D"exec.mainClass=dev.onvoid.webrtc.examples.FileTransferExample" -D"exec.args=50"
52+
* </pre>
53+
*
54+
* @author Alex Andres
55+
*/
56+
public class FileTransferExample {
57+
58+
public static void main(String[] args) throws Exception {
59+
Path downloads = Files.createTempDirectory("webrtc-downloads");
60+
Path source = source(args.length > 0 ? args[0] : "20");
61+
62+
try (WebRtc rtc = WebRtc.builder().audio(AudioMode.HEADLESS).build()) {
63+
// Both peers in one process. A real application signals through its own server.
64+
SignalingPair link = Signaling.loopback();
65+
Peer sender = rtc.createPeer(PeerOptions.builder()
66+
.name("sender")
67+
.signaling(link.first())
68+
.build());
69+
Peer receiver = rtc.createPeer(PeerOptions.builder()
70+
.name("receiver")
71+
.signaling(link.second())
72+
.polite(true)
73+
.build());
74+
75+
CompletableFuture<IncomingTransfer> incoming = new CompletableFuture<>();
76+
77+
receiver.onChannel(channel -> {
78+
if (!channel.label().equals("files")) {
79+
return;
80+
}
81+
82+
FileTransfers.over(channel).onOffer(offer -> {
83+
// The name comes from the remote peer: never use it as a path as it is.
84+
System.out.printf("Receiver is offered %s, %d bytes%n", offer.safeFileName(), offer.size());
85+
incoming.complete(offer.accept(downloads.resolve(offer.safeFileName())));
86+
});
87+
});
88+
89+
FileTransfers files = FileTransfers.over(sender.createChannel("files"));
90+
OutgoingTransfer upload = files.send(source);
91+
92+
upload.onProgress(progress -> System.out.printf("Receiver confirmed %.0f%% (%d of %d bytes)%n",
93+
100 * progress.fraction(), progress.bytes(), progress.size()));
94+
95+
// The main thread may wait; a handler must not.
96+
upload.whenDone().get(60, TimeUnit.SECONDS);
97+
98+
IncomingTransfer received = incoming.get(5, TimeUnit.SECONDS);
99+
received.whenDone().get(5, TimeUnit.SECONDS);
100+
101+
boolean same = Arrays.equals(Files.readAllBytes(source), Files.readAllBytes(received.file()));
102+
103+
System.out.println("Receiver saved " + received.file() + (same ? ", identical to " : ", differing from ")
104+
+ source);
105+
}
106+
}
107+
108+
/**
109+
* @return the file named, or a new file of random data of that many MiB.
110+
*/
111+
private static Path source(String argument) throws Exception {
112+
Path file = Paths.get(argument);
113+
114+
if (Files.isRegularFile(file)) {
115+
return file;
116+
}
117+
118+
byte[] data = new byte[Integer.parseInt(argument) * 1024 * 1024];
119+
new Random().nextBytes(data);
120+
121+
Path random = Files.createTempFile("webrtc-upload", ".bin");
122+
random.toFile().deleteOnExit();
123+
return Files.write(random, data);
124+
}
125+
}

0 commit comments

Comments
 (0)