DataChannelServer
A C++ library for creating WebRTC DataChannel servers.
client.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <iostream>
4 #include <memory>
5 #include <functional>
6 #include <string>
8 #include <DataChannelServer/client-src/internal-api.h>
9 #include <emscripten.h>
10 
13 
14 namespace data_channel {
15 
21  inline void Connect(const std::string &server, int port, std::function<void(std::shared_ptr<DataChannel>)> handler,
22  std::function<void(const std::string &error)> error_handler) {
23  typedef std::function<void(std::shared_ptr<DataChannel>)> ConnectHandler;
24  typedef std::function<void(const std::string &error)> ErrorHandler;
25 
26  CreatePeerConnection(
27  server.c_str(), port,
28  [](PeerConnection *peer, void *data) {
29  ConnectHandler *handler = reinterpret_cast<ConnectHandler *>(data);
30  auto close_handler = [peer]() {
31  std::cout << "LOL SHOULD HAVE QUIT" << std::endl;
32  DeletePeerConnection(peer);
33  };
34 
35  auto message_handler = [peer](const std::string &message) {
36  SendPeerConnectionMessage(peer, message.data(), message.size());
37  };
38 
39  std::shared_ptr<DataChannel> channel =
40  std::make_shared<DataChannel>(message_handler, close_handler);
41 
42  SetOnMessageCallback(
43  peer, [](const char *message, int message_length, void *data) {
44  DataChannel *channel = reinterpret_cast<DataChannel *>(data);
45  std::string message_str(message, message_length);
46  channel->GetOnMessageHandler()(message_str);
47  }, channel.get());
48 
49  SetOnCloseCallback(peer, [](void *data) {
50  DataChannel *channel = reinterpret_cast<DataChannel *>(data);
51  channel->GetOnCloseHandler()();
52  }, channel.get());
53 
54  (*handler)(channel);
55  delete handler;
56  },
57  new ConnectHandler(handler),
58  [](const char *error, int error_length, void *data) {
59  ErrorHandler *handler = reinterpret_cast<ErrorHandler *>(data);
60  std::string error_str(error, error_length);
61  (*handler)(error_str);
62  },
63  new ErrorHandler(error_handler));
64  emscripten_exit_with_live_runtime();
65  }
66 
67 } // namespace data_channel
void Connect(const std::string &server, int port, std::function< void(std::shared_ptr< DataChannel >)> handler, std::function< void(const std::string &error)> error_handler)
Connect to a DataChannel Server.
Definition: client.h:21
A class which represents a single peer connection.
Definition: channel.h:15
The connection API for both the server and client.
Definition: server.h:17