-
Notifications
You must be signed in to change notification settings - Fork 14
Examples
Gil Maimon edited this page Mar 5, 2019
·
2 revisions
This section shows some basic examples for server and client code using the library. More demos can be found in the root library directory (.cpp
files with the prefix demo_
).
Example of basic WebsocketsClient
usage:
#include <tiny_websockets/client.hpp>
#include <iostream>
using namespace websockets;
int main() {
// connect to host
WebsocketsClient client;
client.connect("http://localhost:8080");
// handle messages
client.onMessage([](WebsocketsMessage message) {
std::cout << "Got: " << message.data() << std::endl;
});
// handle events
client.onEvent([](WebsocketsEvent event, std::string data) {
// Handle "Pings", "Pongs" and other events
});
// send a message
client.send("Hi Server!");
while(client.available()) {
// wait for server messages and events
client.poll();
}
}
Example of basic WebsocketsServer
usage:
#include <tiny_websockets/server.hpp>
#include <iostream>
using namespace websockets;
int main() {
WebsocketsServer server;
server.listen(8080);
// while possible
while(server.available()) {
// accept another client
WebsocketsClient client = server.accept();
// wait for a message for the client and send an echo response
auto message = client.readBlocking();
client.send("Echo: " + message.data());
// close the connection
client.close();
}
}
The basic examples presented here cover most of what there is to know about the library. For more examples, features and API Reference go to the next sections.
Next: API Reference
Written by Gil Maimon @ 2019