This is possible!
Can be done with the ESPAsyncWebServer.
https://github.com/me-no-dev/ESPAsyncWebServer#why-should-you-care
#include <AsyncEventSource.h>
#include <AsyncJson.h>
#include <AsyncWebSocket.h
#include <AsyncWebSynchronization.h>
#include <ESPAsyncWebSrv.h>
#include <SPIFFSEditor.h>
#include <StringArray.h>
#include <WebAuthentication.h>
#include <WebHandlerImpl.h>
#include <WebResponseImpl.h>
#include <WiFi.h>
const char* ssid = "";
const char* password = "";
AsyncWebServer server(80);
AsyncWebSocket ws("/ws");
int counter = 0;
void initWebServer() {
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
String html = "<html><body><h1>Hello World</h1>";
html += "<button type='submit'>Increment Counter</button>";
html += "</form>";
// Add script tag with WebSocket code
html += "<script>var ws = new WebSocket('ws://' + window.location.host + '/ws');";
html += "ws.onopen = function(event) { console.log('WebSocket connected.'); };</script>";
html += "</body></html>";
request->send(200, "text/html", html);
});
server.on("/increment", HTTP_POST, [](AsyncWebServerRequest *request){
counter++;
request->redirect("/");
});
ws.onEvent([](AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len){
if(type == WS_EVT_CONNECT){
Serial.println("WebSocket client connected");
client->text("Hello, Client!");
}
else if(type == WS_EVT_DISCONNECT){
Serial.println("WebSocket client disconnected");
}
else if(type == WS_EVT_DATA){
Serial.print("WebSocket client message received: ");
Serial.write(data, len);
Serial.println();
client->text("Echo: " + String((char*)data));
}
});
server.addHandler(&ws);
server.begin();
Serial.println("Web server started");
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("WiFi connected");
initWebServer();
}
void loop() {
}