Skip to content

Commit b772299

Browse files
committed
Tunnel
1 parent 180d6fe commit b772299

2 files changed

Lines changed: 198 additions & 1 deletion

File tree

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
// SPDX-License-Identifier: LGPL-3.0-or-later
2+
// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov
3+
4+
//
5+
// Shows how to trigger an async client request from a browser request and send the client response back to the browser through websocket
6+
//
7+
8+
#include <Arduino.h>
9+
#ifdef ESP32
10+
#include <AsyncTCP.h>
11+
#include <WiFi.h>
12+
#elif defined(ESP8266)
13+
#include <ESP8266WiFi.h>
14+
#include <ESPAsyncTCP.h>
15+
#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350)
16+
#include <RPAsyncTCP.h>
17+
#include <WiFi.h>
18+
#endif
19+
20+
#include <ESPAsyncWebServer.h>
21+
22+
#define WIFI_SSID "IoT"
23+
#define WIFI_PASSWORD ""
24+
25+
static AsyncWebServer server(80);
26+
static AsyncWebSocketMessageHandler wsHandler;
27+
static AsyncWebSocket ws("/ws", wsHandler.eventHandler());
28+
29+
static const char *htmlContent PROGMEM = R"(
30+
<!DOCTYPE html>
31+
<html>
32+
<head>
33+
<title>WebSocket Tunnel Example</title>
34+
</head>
35+
<body>
36+
<h1>WebSocket Tunnel Example</h1>
37+
<div><input type="text" id="url" value="http://www.google.com" /></div>
38+
<div><button onclick='fetch()'>Fetch</button></div>
39+
<div><pre id="response"></pre></div>
40+
<script>
41+
var ws = new WebSocket('/ws');
42+
ws.onopen = function() {
43+
console.log("WebSocket connected");
44+
};
45+
ws.onmessage = function(event) {
46+
console.log("WebSocket message: " + event.data);
47+
document.getElementById("response").innerText += event.data;
48+
};
49+
ws.onclose = function() {
50+
console.log("WebSocket closed");
51+
};
52+
ws.onerror = function(error) {
53+
console.log("WebSocket error: " + error);
54+
};
55+
function fetch() {
56+
document.getElementById("response").innerText = "";
57+
var url = document.getElementById("url").value;
58+
ws.send(url);
59+
console.log("WebSocket sent: " + url);
60+
}
61+
</script>
62+
</body>
63+
</html>
64+
)";
65+
static const size_t htmlContentLength = strlen_P(htmlContent);
66+
67+
void setup() {
68+
Serial.begin(115200);
69+
70+
#ifndef CONFIG_IDF_TARGET_ESP32H2
71+
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
72+
while (WiFi.status() != WL_CONNECTED) {
73+
delay(500);
74+
}
75+
Serial.println("Connected to WiFi!");
76+
Serial.println(WiFi.localIP());
77+
#endif
78+
79+
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
80+
request->send(200, "text/html", (const uint8_t *)htmlContent, htmlContentLength);
81+
});
82+
83+
wsHandler.onMessage([](AsyncWebSocket *server, AsyncWebSocketClient *wsClient, const uint8_t *data, size_t len) {
84+
String url = String((const char *)data, len);
85+
String host;
86+
String port;
87+
String path;
88+
89+
if (!url.startsWith("http://")) {
90+
return;
91+
}
92+
93+
if (!url.endsWith("/")) {
94+
url += "/";
95+
}
96+
97+
// Parse the URL to extract the host and port
98+
int start = url.indexOf("://") + 3;
99+
int end = url.indexOf("/", start);
100+
if (end == -1) {
101+
end = url.length();
102+
}
103+
String hostPort = url.substring(start, end);
104+
int colonIndex = hostPort.indexOf(":");
105+
if (colonIndex != -1) {
106+
host = hostPort.substring(0, colonIndex);
107+
port = hostPort.substring(colonIndex + 1);
108+
} else {
109+
host = hostPort;
110+
port = "80"; // Default HTTP port
111+
}
112+
path = url.substring(end);
113+
114+
Serial.printf("Host: %s\n", host.c_str());
115+
Serial.printf("Port: %s\n", port.c_str());
116+
Serial.printf("Path: %s\n", path.c_str());
117+
118+
// Ensure client does not get deleted while the websocket holds a reference to it
119+
std::shared_ptr<AsyncClient> *safeAsyncClient = new std::shared_ptr<AsyncClient>(std::make_shared<AsyncClient>());
120+
AsyncClient *asyncClient = safeAsyncClient->get();
121+
122+
// when client disconnects, we clear the buffer which signals the end of the chunk request
123+
// note: onDisconnect also called on error
124+
asyncClient->onDisconnect([safeAsyncClient](void *arg, AsyncClient *client) {
125+
Serial.printf("Tunnel disconnected!\n");
126+
delete safeAsyncClient;
127+
});
128+
129+
// register a callback when an error occurs
130+
asyncClient->onError([](void *arg, AsyncClient *client, int8_t error) {
131+
Serial.printf("Tunnel error: %s\n", client->errorToString(error));
132+
});
133+
134+
// register a callback when data arrives, to accumulate it
135+
asyncClient->onPacket(
136+
[safeAsyncClient](void *arg, AsyncClient *, struct pbuf *pb) {
137+
std::shared_ptr<AsyncClient> safeAsyncClientRef = *safeAsyncClient; // add a reference
138+
AsyncWebSocketClient *wsClient = (AsyncWebSocketClient *)arg;
139+
Serial.printf("Tunnel received %u bytes\n", pb->len);
140+
pbuf_ref(pb); // Increment pbuf reference count so it doesn't get freed prematurely
141+
AsyncWebSocketSharedBuffer wsBuffer =
142+
AsyncWebSocketSharedBuffer(new std::vector<uint8_t>((uint8_t *)pb->payload, (uint8_t *)pb->payload + pb->len), [=](std::vector<uint8_t> *bufptr) {
143+
delete bufptr;
144+
Serial.printf("ACK %u bytes\n", pb->len);
145+
safeAsyncClientRef->ackPacket(pb);
146+
});
147+
Serial.printf("Tunnel sending %u bytes\n", wsBuffer->size());
148+
Serial.printf("%.*s\n", (int)wsBuffer->size(), wsBuffer->data());
149+
wsClient->text(std::move(wsBuffer));
150+
},
151+
wsClient
152+
);
153+
154+
asyncClient->onConnect([=](void *arg, AsyncClient *client) {
155+
Serial.printf("Tunnel connected!\n");
156+
157+
client->write("GET ");
158+
client->write(path.c_str());
159+
client->write(" HTTP/1.1\r\n");
160+
client->write("Host: ");
161+
client->write(host.c_str());
162+
client->write(":");
163+
client->write(port.c_str());
164+
client->write("\r\n");
165+
client->write("User-Agent: ESP32\r\n");
166+
client->write("Accept: */*\r\n");
167+
client->write("Connection: close\r\n");
168+
client->write("\r\n");
169+
});
170+
171+
Serial.printf("Fetching: http://%s:%s%s\n", host.c_str(), port.c_str(), path.c_str());
172+
173+
if (!asyncClient->connect(host.c_str(), port.toInt())) {
174+
Serial.printf("Failed to open tunnel!\n");
175+
delete safeAsyncClient;
176+
}
177+
});
178+
179+
wsHandler.onConnect([](AsyncWebSocket *server, AsyncWebSocketClient *client) {
180+
Serial.printf("Client %" PRIu32 " connected\n", client->id());
181+
client->text("WebSocket connected!");
182+
});
183+
184+
wsHandler.onDisconnect([](AsyncWebSocket *server, uint32_t clientId) {
185+
Serial.printf("Client %" PRIu32 " disconnected\n", clientId);
186+
});
187+
188+
server.addHandler(&ws);
189+
server.begin();
190+
Serial.println("Server started!");
191+
}
192+
193+
void loop() {
194+
ws.cleanupClients(2);
195+
delay(500);
196+
}

platformio.ini

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
default_envs = arduino-2, arduino-3, esp8266, raspberrypi
33
lib_dir = .
44
; src_dir = examples/AsyncResponseStream
5+
src_dir = examples/AsyncTunnel
56
; src_dir = examples/Auth
67
; src_dir = examples/CaptivePortal
78
; src_dir = examples/CatchAllHandler
@@ -18,7 +19,7 @@ lib_dir = .
1819
; src_dir = examples/Middleware
1920
; src_dir = examples/Params
2021
; src_dir = examples/PartitionDownloader
21-
src_dir = examples/PerfTests
22+
; src_dir = examples/PerfTests
2223
; src_dir = examples/RateLimit
2324
; src_dir = examples/Redirect
2425
; src_dir = examples/RequestContinuation

0 commit comments

Comments
 (0)