On Tue, 28 May 2024 12:19:26 GMT, MrX wrote:
Hello,
Could someone share an example on how to execute a ping/pong through a WebSocket?
Thank you.
There are two existing examples:
https://github.com/vibe-d/vibe-http/tree/master/examples/websocket
https://vibed.org/blog/posts/a-scalable-chat-room-service-in-d
In particular, the first example could be extended with a client-side part roughly like this:
connectWebSocket("http://127.0.0.1:8080/ws", (scope ws) {
while (ws.waitForData) {
auto message = ws.receiveText();
logInfo("Received message from server: %s", message);
ws.send("PONG");
}
});
The complete example then looks like this:
module app;
import vibe.core.core;
import vibe.core.log;
import vibe.http.fileserver : serveStaticFiles;
import vibe.http.router : URLRouter;
import vibe.http.server;
import vibe.http.websockets : WebSocket, handleWebSockets, connectWebSocket;
import vibe.inet.url : URL;
import core.time;
import std.conv : to;
int main(string[] args)
{
auto router = new URLRouter;
router.get("/", staticRedirect("/index.html"));
router.get("/ws", handleWebSockets(&handleWebSocketConnection));
router.get("*", serveStaticFiles("public/"));
auto settings = new HTTPServerSettings;
settings.port = 8080;
settings.bindAddresses = ["::1", "127.0.0.1"];
auto listener = listenHTTP(settings, router);
// connect to the web socket endpoint and reply to all messages received
runTask({
try connectWebSocket(URL("http://127.0.0.1:8080/ws"), (scope socket) {
while (socket.waitForData) {
auto message = socket.receiveText();
logInfo("Received message from server: %s", message);
socket.send("PONG");
}
});
catch (Exception e) logException(e, "Failed to connect web socket");
});
return runApplication(&args);
}
void handleWebSocketConnection(scope WebSocket socket)
{
int counter = 0;
logInfo("Got new web socket connection.");
// read replies as long as the connection is active
runTask({
try {
while (socket.waitForData) {
auto message = socket.receiveText();
logInfo("Received message from client: %s", message);
}
} catch (Exception e) logException(e, "Failed to receive web socket message");
});
while (true) {
sleep(1.seconds);
if (!socket.connected) break;
counter++;
logInfo("Sending '%s'.", counter);
socket.send(counter.to!string);
}
logInfo("Client disconnected.");
}
The send and receive operations can be separated into different loops running in different tasks, as on the server side here, or can be made is sequence, as on the client side, depending on what the protocol requires.