Skip to content

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_).

Client

Example of basic WebsocketsClient usage.

This program will connect to a local websockets server running on port 8080. After connecting to the server, the client will send "Hi Server!" and will wait for messages and events in response.

#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();
  }
}

Server

Example of basic WebsocketsServer usage.

This program will start a basic echo server on port 8080. It will wait for clients, accept the connection and wait for a message from them. Once a message is received, the server will send an echo response. So if the client sent an "Hello World" the server will respond with "Echo: Hello World". After that, the server will close the connection and will wait for the next client.

#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();
  }
}

Whats Next?

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

Clone this wiki locally