2020-05-28 01:24:33 +02:00
|
|
|
/*
|
|
|
|
* main.cpp
|
|
|
|
* Author: Benjamin Sergeant
|
|
|
|
* Copyright (c) 2020 Machine Zone, Inc. All rights reserved.
|
|
|
|
*
|
|
|
|
* Super simple standalone example. See ws folder, unittest and doc/usage.md for more.
|
|
|
|
*
|
|
|
|
* On macOS
|
|
|
|
* $ mkdir -p build ; cd build ; cmake -DUSE_TLS=1 .. ; make -j ; make install
|
|
|
|
* $ clang++ --std=c++14 --stdlib=libc++ main.cpp -lixwebsocket -lz -framework Security -framework Foundation
|
|
|
|
* $ ./a.out
|
2021-03-22 16:51:58 +01:00
|
|
|
*
|
|
|
|
* Or use cmake -DBUILD_DEMO=ON option for other platform
|
2020-05-28 01:24:33 +02:00
|
|
|
*/
|
|
|
|
|
|
|
|
#include <ixwebsocket/IXNetSystem.h>
|
|
|
|
#include <ixwebsocket/IXWebSocket.h>
|
|
|
|
#include <iostream>
|
|
|
|
|
|
|
|
int main()
|
|
|
|
{
|
|
|
|
// Required on Windows
|
|
|
|
ix::initNetSystem();
|
|
|
|
|
|
|
|
// Our websocket object
|
|
|
|
ix::WebSocket webSocket;
|
|
|
|
|
|
|
|
std::string url("wss://echo.websocket.org");
|
|
|
|
webSocket.setUrl(url);
|
|
|
|
|
|
|
|
std::cout << "Connecting to " << url << "..." << std::endl;
|
|
|
|
|
|
|
|
// Setup a callback to be fired (in a background thread, watch out for race conditions !)
|
|
|
|
// when a message or an event (open, close, error) is received
|
|
|
|
webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg)
|
|
|
|
{
|
|
|
|
if (msg->type == ix::WebSocketMessageType::Message)
|
|
|
|
{
|
|
|
|
std::cout << "received message: " << msg->str << std::endl;
|
2021-02-19 22:49:55 +01:00
|
|
|
std::cout << "> " << std::flush;
|
2020-05-28 01:24:33 +02:00
|
|
|
}
|
|
|
|
else if (msg->type == ix::WebSocketMessageType::Open)
|
|
|
|
{
|
|
|
|
std::cout << "Connection established" << std::endl;
|
2021-02-19 22:49:55 +01:00
|
|
|
std::cout << "> " << std::flush;
|
2020-05-28 01:24:33 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
|
|
|
// Now that our callback is setup, we can start our background thread and receive messages
|
|
|
|
webSocket.start();
|
|
|
|
|
|
|
|
// Send a message to the server (default to TEXT mode)
|
|
|
|
webSocket.send("hello world");
|
|
|
|
|
2021-02-19 22:49:55 +01:00
|
|
|
// Display a prompt
|
|
|
|
std::cout << "> " << std::flush;
|
2020-05-28 01:24:33 +02:00
|
|
|
|
2021-02-19 22:49:55 +01:00
|
|
|
std::string text;
|
|
|
|
// Read text from the console and send messages in text mode.
|
|
|
|
// Exit with Ctrl-D on Unix or Ctrl-Z on Windows.
|
|
|
|
while (std::getline(std::cin, text))
|
|
|
|
{
|
2020-05-28 01:24:33 +02:00
|
|
|
webSocket.send(text);
|
2021-02-19 22:49:55 +01:00
|
|
|
std::cout << "> " << std::flush;
|
2020-05-28 01:24:33 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|