Skip to content

Commit e175568

Browse files
committed
Update WebSocket example
1 parent b170b9d commit e175568

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

examples/WebSocket/WebSocket.ino

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,42 @@
1919

2020
#include <ESPAsyncWebServer.h>
2121

22+
static const char *htmlContent PROGMEM = R"(
23+
<!DOCTYPE html>
24+
<html>
25+
<head>
26+
<title>WebSocket</title>
27+
</head>
28+
<body>
29+
<h1>WebSocket Example</h1>
30+
<p>Open your browser console!</p>
31+
<input type="text" id="message" placeholder="Type a message">
32+
<button onclick='sendMessage()'>Send</button>
33+
<script>
34+
var ws = new WebSocket('ws://192.168.4.1/ws');
35+
ws.onopen = function() {
36+
console.log("WebSocket connected");
37+
};
38+
ws.onmessage = function(event) {
39+
console.log("WebSocket message: " + event.data);
40+
};
41+
ws.onclose = function() {
42+
console.log("WebSocket closed");
43+
};
44+
ws.onerror = function(error) {
45+
console.log("WebSocket error: " + error);
46+
};
47+
function sendMessage() {
48+
var message = document.getElementById("message").value;
49+
ws.send(message);
50+
console.log("WebSocket sent: " + message);
51+
}
52+
</script>
53+
</body>
54+
</html>
55+
)";
56+
static const size_t htmlContentLength = strlen_P(htmlContent);
57+
2258
static AsyncWebServer server(80);
2359
static AsyncWebSocket ws("/ws");
2460

@@ -30,6 +66,11 @@ void setup() {
3066
WiFi.softAP("esp-captive");
3167
#endif
3268

69+
// serves root html page
70+
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
71+
request->send(200, "text/html", (const uint8_t *)htmlContent, htmlContentLength);
72+
});
73+
3374
//
3475
// Run in terminal 1: websocat ws://192.168.4.1/ws => should stream data
3576
// Run in terminal 2: websocat ws://192.168.4.1/ws => should stream data

examples/WebSocketEasy/WebSocketEasy.ino

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ static const char *htmlContent PROGMEM = R"(
4040
</head>
4141
<body>
4242
<h1>WebSocket Example</h1>
43-
<>Open your browser console!</p>
43+
<p>Open your browser console!</p>
4444
<input type="text" id="message" placeholder="Type a message">
4545
<button onclick='sendMessage()'>Send</button>
4646
<script>

0 commit comments

Comments
 (0)