reformat everything with clang-format
This commit is contained in:
@ -4,14 +4,13 @@
|
||||
* Copyright (c) 2017 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
#include "IXSnakeServer.h"
|
||||
#include "IXTest.h"
|
||||
#include "catch.hpp"
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <ixcobra/IXCobraConnection.h>
|
||||
#include <ixcrypto/IXUuid.h>
|
||||
#include "IXTest.h"
|
||||
#include "IXSnakeServer.h"
|
||||
|
||||
#include "catch.hpp"
|
||||
|
||||
using namespace ix;
|
||||
|
||||
@ -22,67 +21,64 @@ namespace
|
||||
|
||||
void setupTrafficTrackerCallback()
|
||||
{
|
||||
ix::CobraConnection::setTrafficTrackerCallback(
|
||||
[](size_t size, bool incoming)
|
||||
ix::CobraConnection::setTrafficTrackerCallback([](size_t size, bool incoming) {
|
||||
if (incoming)
|
||||
{
|
||||
if (incoming)
|
||||
{
|
||||
incomingBytes += size;
|
||||
}
|
||||
else
|
||||
{
|
||||
outgoingBytes += size;
|
||||
}
|
||||
incomingBytes += size;
|
||||
}
|
||||
);
|
||||
else
|
||||
{
|
||||
outgoingBytes += size;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
class SatoriChat
|
||||
{
|
||||
public:
|
||||
SatoriChat(const std::string& user,
|
||||
const std::string& session,
|
||||
const std::string& endpoint);
|
||||
public:
|
||||
SatoriChat(const std::string& user,
|
||||
const std::string& session,
|
||||
const std::string& endpoint);
|
||||
|
||||
void subscribe(const std::string& channel);
|
||||
void start();
|
||||
void stop();
|
||||
void run();
|
||||
bool isReady() const;
|
||||
void subscribe(const std::string& channel);
|
||||
void start();
|
||||
void stop();
|
||||
void run();
|
||||
bool isReady() const;
|
||||
|
||||
void sendMessage(const std::string& text);
|
||||
size_t getReceivedMessagesCount() const;
|
||||
void sendMessage(const std::string& text);
|
||||
size_t getReceivedMessagesCount() const;
|
||||
|
||||
bool hasPendingMessages() const;
|
||||
Json::Value popMessage();
|
||||
bool hasPendingMessages() const;
|
||||
Json::Value popMessage();
|
||||
|
||||
private:
|
||||
std::string _user;
|
||||
std::string _session;
|
||||
std::string _endpoint;
|
||||
private:
|
||||
std::string _user;
|
||||
std::string _session;
|
||||
std::string _endpoint;
|
||||
|
||||
std::queue<Json::Value> _publish_queue;
|
||||
mutable std::mutex _queue_mutex;
|
||||
std::queue<Json::Value> _publish_queue;
|
||||
mutable std::mutex _queue_mutex;
|
||||
|
||||
std::thread _thread;
|
||||
std::atomic<bool> _stop;
|
||||
std::thread _thread;
|
||||
std::atomic<bool> _stop;
|
||||
|
||||
ix::CobraConnection _conn;
|
||||
std::atomic<bool> _connectedAndSubscribed;
|
||||
ix::CobraConnection _conn;
|
||||
std::atomic<bool> _connectedAndSubscribed;
|
||||
|
||||
std::queue<Json::Value> _receivedQueue;
|
||||
std::queue<Json::Value> _receivedQueue;
|
||||
|
||||
std::mutex _logMutex;
|
||||
std::mutex _logMutex;
|
||||
};
|
||||
|
||||
SatoriChat::SatoriChat(const std::string& user,
|
||||
const std::string& session,
|
||||
const std::string& endpoint) :
|
||||
_user(user),
|
||||
_session(session),
|
||||
_endpoint(endpoint),
|
||||
_stop(false),
|
||||
_connectedAndSubscribed(false)
|
||||
const std::string& endpoint)
|
||||
: _user(user)
|
||||
, _session(session)
|
||||
, _endpoint(endpoint)
|
||||
, _stop(false)
|
||||
, _connectedAndSubscribed(false)
|
||||
{
|
||||
}
|
||||
|
||||
@ -127,35 +123,30 @@ namespace
|
||||
void SatoriChat::subscribe(const std::string& channel)
|
||||
{
|
||||
std::string filter;
|
||||
_conn.subscribe(channel, filter,
|
||||
[this](const Json::Value& msg)
|
||||
{
|
||||
std::cout << msg.toStyledString() << std::endl;
|
||||
if (!msg.isObject()) return;
|
||||
if (!msg.isMember("user")) return;
|
||||
if (!msg.isMember("text")) return;
|
||||
if (!msg.isMember("session")) return;
|
||||
_conn.subscribe(channel, filter, [this](const Json::Value& msg) {
|
||||
std::cout << msg.toStyledString() << std::endl;
|
||||
if (!msg.isObject()) return;
|
||||
if (!msg.isMember("user")) return;
|
||||
if (!msg.isMember("text")) return;
|
||||
if (!msg.isMember("session")) return;
|
||||
|
||||
std::string msg_user = msg["user"].asString();
|
||||
std::string msg_text = msg["text"].asString();
|
||||
std::string msg_session = msg["session"].asString();
|
||||
std::string msg_user = msg["user"].asString();
|
||||
std::string msg_text = msg["text"].asString();
|
||||
std::string msg_session = msg["session"].asString();
|
||||
|
||||
// We are not interested in messages
|
||||
// from a different session.
|
||||
if (msg_session != _session) return;
|
||||
// We are not interested in messages
|
||||
// from a different session.
|
||||
if (msg_session != _session) return;
|
||||
|
||||
// We are not interested in our own messages
|
||||
if (msg_user == _user) return;
|
||||
// We are not interested in our own messages
|
||||
if (msg_user == _user) return;
|
||||
|
||||
_receivedQueue.push(msg);
|
||||
_receivedQueue.push(msg);
|
||||
|
||||
std::stringstream ss;
|
||||
ss << std::endl
|
||||
<< msg_user << " > " << msg_text
|
||||
<< std::endl
|
||||
<< _user << " > ";
|
||||
log(ss.str());
|
||||
});
|
||||
std::stringstream ss;
|
||||
ss << std::endl << msg_user << " > " << msg_text << std::endl << _user << " > ";
|
||||
log(ss.str());
|
||||
});
|
||||
}
|
||||
|
||||
void SatoriChat::sendMessage(const std::string& text)
|
||||
@ -189,50 +180,46 @@ namespace
|
||||
std::string role = "_sub";
|
||||
std::string secret = "66B1dA3ED5fA074EB5AE84Dd8CE3b5ba";
|
||||
|
||||
_conn.configure(appkey, _endpoint, role, secret,
|
||||
ix::WebSocketPerMessageDeflateOptions(true));
|
||||
_conn.configure(
|
||||
appkey, _endpoint, role, secret, ix::WebSocketPerMessageDeflateOptions(true));
|
||||
_conn.connect();
|
||||
|
||||
_conn.setEventCallback(
|
||||
[this, channel]
|
||||
(ix::CobraConnectionEventType eventType,
|
||||
const std::string& errMsg,
|
||||
const ix::WebSocketHttpHeaders& /*headers*/,
|
||||
const std::string& subscriptionId,
|
||||
CobraConnection::MsgId msgId)
|
||||
_conn.setEventCallback([this, channel](ix::CobraConnectionEventType eventType,
|
||||
const std::string& errMsg,
|
||||
const ix::WebSocketHttpHeaders& /*headers*/,
|
||||
const std::string& subscriptionId,
|
||||
CobraConnection::MsgId msgId) {
|
||||
if (eventType == ix::CobraConnection_EventType_Open)
|
||||
{
|
||||
if (eventType == ix::CobraConnection_EventType_Open)
|
||||
{
|
||||
log("Subscriber connected: " + _user);
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Authenticated)
|
||||
{
|
||||
log("Subscriber authenticated: " + _user);
|
||||
subscribe(channel);
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Error)
|
||||
{
|
||||
log(errMsg + _user);
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Closed)
|
||||
{
|
||||
log("Connection closed: " + _user);
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Subscribed)
|
||||
{
|
||||
log("Subscription ok: " + _user + " subscription_id " + subscriptionId);
|
||||
_connectedAndSubscribed = true;
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_UnSubscribed)
|
||||
{
|
||||
log("Unsubscription ok: " + _user + " subscription_id " + subscriptionId);
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Published)
|
||||
{
|
||||
Logger() << "Subscriber: published message acked: " << msgId;
|
||||
}
|
||||
log("Subscriber connected: " + _user);
|
||||
}
|
||||
);
|
||||
else if (eventType == ix::CobraConnection_EventType_Authenticated)
|
||||
{
|
||||
log("Subscriber authenticated: " + _user);
|
||||
subscribe(channel);
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Error)
|
||||
{
|
||||
log(errMsg + _user);
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Closed)
|
||||
{
|
||||
log("Connection closed: " + _user);
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Subscribed)
|
||||
{
|
||||
log("Subscription ok: " + _user + " subscription_id " + subscriptionId);
|
||||
_connectedAndSubscribed = true;
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_UnSubscribed)
|
||||
{
|
||||
log("Unsubscription ok: " + _user + " subscription_id " + subscriptionId);
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Published)
|
||||
{
|
||||
Logger() << "Subscriber: published message acked: " << msgId;
|
||||
}
|
||||
});
|
||||
|
||||
while (!_stop)
|
||||
{
|
||||
@ -261,19 +248,15 @@ namespace
|
||||
ix::msleep(50);
|
||||
_conn.disconnect();
|
||||
|
||||
_conn.setEventCallback([]
|
||||
(ix::CobraConnectionEventType /*eventType*/,
|
||||
const std::string& /*errMsg*/,
|
||||
const ix::WebSocketHttpHeaders& /*headers*/,
|
||||
const std::string& /*subscriptionId*/,
|
||||
CobraConnection::MsgId /*msgId*/)
|
||||
{
|
||||
;
|
||||
});
|
||||
_conn.setEventCallback([](ix::CobraConnectionEventType /*eventType*/,
|
||||
const std::string& /*errMsg*/,
|
||||
const ix::WebSocketHttpHeaders& /*headers*/,
|
||||
const std::string& /*subscriptionId*/,
|
||||
CobraConnection::MsgId /*msgId*/) { ; });
|
||||
|
||||
snakeServer.stop();
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Cobra_chat", "[cobra_chat]")
|
||||
{
|
||||
|
@ -3,14 +3,13 @@
|
||||
* Copyright (c) 2018 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
#include <set>
|
||||
#include <ixcrypto/IXUuid.h>
|
||||
#include <ixcobra/IXCobraMetricsPublisher.h>
|
||||
#include "IXTest.h"
|
||||
#include "IXSnakeServer.h"
|
||||
|
||||
#include "IXTest.h"
|
||||
#include "catch.hpp"
|
||||
#include <iostream>
|
||||
#include <ixcobra/IXCobraMetricsPublisher.h>
|
||||
#include <ixcrypto/IXUuid.h>
|
||||
#include <set>
|
||||
|
||||
using namespace ix;
|
||||
|
||||
@ -45,70 +44,67 @@ namespace
|
||||
gMessageCount = 0;
|
||||
|
||||
ix::CobraConnection conn;
|
||||
conn.configure(APPKEY, endpoint, SUBSCRIBER_ROLE, SUBSCRIBER_SECRET,
|
||||
conn.configure(APPKEY,
|
||||
endpoint,
|
||||
SUBSCRIBER_ROLE,
|
||||
SUBSCRIBER_SECRET,
|
||||
ix::WebSocketPerMessageDeflateOptions(true));
|
||||
conn.connect();
|
||||
|
||||
conn.setEventCallback(
|
||||
[&conn]
|
||||
(ix::CobraConnectionEventType eventType,
|
||||
const std::string& errMsg,
|
||||
const ix::WebSocketHttpHeaders& /*headers*/,
|
||||
const std::string& subscriptionId,
|
||||
CobraConnection::MsgId msgId)
|
||||
conn.setEventCallback([&conn](ix::CobraConnectionEventType eventType,
|
||||
const std::string& errMsg,
|
||||
const ix::WebSocketHttpHeaders& /*headers*/,
|
||||
const std::string& subscriptionId,
|
||||
CobraConnection::MsgId msgId) {
|
||||
if (eventType == ix::CobraConnection_EventType_Open)
|
||||
{
|
||||
if (eventType == ix::CobraConnection_EventType_Open)
|
||||
{
|
||||
Logger() << "Subscriber connected:";
|
||||
}
|
||||
if (eventType == ix::CobraConnection_EventType_Error)
|
||||
{
|
||||
Logger() << "Subscriber error:" << errMsg;
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Authenticated)
|
||||
{
|
||||
log("Subscriber authenticated");
|
||||
std::string filter;
|
||||
conn.subscribe(CHANNEL, filter,
|
||||
[](const Json::Value& msg)
|
||||
{
|
||||
log(msg.toStyledString());
|
||||
Logger() << "Subscriber connected:";
|
||||
}
|
||||
if (eventType == ix::CobraConnection_EventType_Error)
|
||||
{
|
||||
Logger() << "Subscriber error:" << errMsg;
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Authenticated)
|
||||
{
|
||||
log("Subscriber authenticated");
|
||||
std::string filter;
|
||||
conn.subscribe(CHANNEL, filter, [](const Json::Value& msg) {
|
||||
log(msg.toStyledString());
|
||||
|
||||
std::string id = msg["id"].asString();
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(gProtectIds);
|
||||
gIds.insert(id);
|
||||
}
|
||||
std::string id = msg["id"].asString();
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(gProtectIds);
|
||||
gIds.insert(id);
|
||||
}
|
||||
|
||||
gMessageCount++;
|
||||
});
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Subscribed)
|
||||
gMessageCount++;
|
||||
});
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Subscribed)
|
||||
{
|
||||
Logger() << "Subscriber: subscribed to channel " << subscriptionId;
|
||||
if (subscriptionId == CHANNEL)
|
||||
{
|
||||
Logger() << "Subscriber: subscribed to channel " << subscriptionId;
|
||||
if (subscriptionId == CHANNEL)
|
||||
{
|
||||
gSubscriberConnectedAndSubscribed = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger() << "Subscriber: unexpected channel " << subscriptionId;
|
||||
}
|
||||
gSubscriberConnectedAndSubscribed = true;
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_UnSubscribed)
|
||||
else
|
||||
{
|
||||
Logger() << "Subscriber: ununexpected from channel " << subscriptionId;
|
||||
if (subscriptionId != CHANNEL)
|
||||
{
|
||||
Logger() << "Subscriber: unexpected channel " << subscriptionId;
|
||||
}
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Published)
|
||||
{
|
||||
Logger() << "Subscriber: published message acked: " << msgId;
|
||||
Logger() << "Subscriber: unexpected channel " << subscriptionId;
|
||||
}
|
||||
}
|
||||
);
|
||||
else if (eventType == ix::CobraConnection_EventType_UnSubscribed)
|
||||
{
|
||||
Logger() << "Subscriber: ununexpected from channel " << subscriptionId;
|
||||
if (subscriptionId != CHANNEL)
|
||||
{
|
||||
Logger() << "Subscriber: unexpected channel " << subscriptionId;
|
||||
}
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Published)
|
||||
{
|
||||
Logger() << "Subscriber: published message acked: " << msgId;
|
||||
}
|
||||
});
|
||||
|
||||
while (!gStop)
|
||||
{
|
||||
@ -121,7 +117,7 @@ namespace
|
||||
|
||||
gUniqueMessageIdsCount = gIds.size();
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Cobra_Metrics_Publisher", "[cobra]")
|
||||
{
|
||||
@ -158,8 +154,8 @@ TEST_CASE("Cobra_Metrics_Publisher", "[cobra]")
|
||||
ix::CobraMetricsPublisher cobraMetricsPublisher;
|
||||
|
||||
bool perMessageDeflate = true;
|
||||
cobraMetricsPublisher.configure(APPKEY, endpoint, CHANNEL,
|
||||
PUBLISHER_ROLE, PUBLISHER_SECRET, perMessageDeflate);
|
||||
cobraMetricsPublisher.configure(
|
||||
APPKEY, endpoint, CHANNEL, PUBLISHER_ROLE, PUBLISHER_SECRET, perMessageDeflate);
|
||||
cobraMetricsPublisher.setSession(uuid4());
|
||||
cobraMetricsPublisher.enable(true); // disabled by default, needs to be enabled to be active
|
||||
|
||||
@ -189,7 +185,7 @@ TEST_CASE("Cobra_Metrics_Publisher", "[cobra]")
|
||||
|
||||
// (msg #6)
|
||||
cobraMetricsPublisher.setRateControl({
|
||||
{"sms_metric_C_id", 1}, // published once per minute (60 seconds) max
|
||||
{"sms_metric_C_id", 1}, // published once per minute (60 seconds) max
|
||||
});
|
||||
// (msg #7)
|
||||
cobraMetricsPublisher.push("sms_metric_C_id", data);
|
||||
@ -205,7 +201,7 @@ TEST_CASE("Cobra_Metrics_Publisher", "[cobra]")
|
||||
log("Testing suspend/resume now, which will disconnect the cobraMetricsPublisher.");
|
||||
|
||||
// Test suspend + resume
|
||||
for (int i = 0 ; i < 3 ; ++i)
|
||||
for (int i = 0; i < 3; ++i)
|
||||
{
|
||||
cobraMetricsPublisher.suspend();
|
||||
ix::msleep(500);
|
||||
@ -214,7 +210,7 @@ TEST_CASE("Cobra_Metrics_Publisher", "[cobra]")
|
||||
cobraMetricsPublisher.push("sms_metric_D_id", data); // will not be sent this time
|
||||
|
||||
cobraMetricsPublisher.resume();
|
||||
ix::msleep(2000); // give cobra 2s to connect
|
||||
ix::msleep(2000); // give cobra 2s to connect
|
||||
REQUIRE(cobraMetricsPublisher.isConnected()); // Check that we are connected now
|
||||
|
||||
cobraMetricsPublisher.push("sms_metric_E_id", data);
|
||||
|
@ -4,11 +4,10 @@
|
||||
* Copyright (c) 2018 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "catch.hpp"
|
||||
|
||||
#include "IXTest.h"
|
||||
#include <ixwebsocket/IXDNSLookup.h>
|
||||
#include "catch.hpp"
|
||||
#include <iostream>
|
||||
#include <ixwebsocket/IXDNSLookup.h>
|
||||
|
||||
using namespace ix;
|
||||
|
||||
@ -32,7 +31,11 @@ TEST_CASE("dns", "[net]")
|
||||
auto dnsLookup = std::make_shared<DNSLookup>("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww", 80);
|
||||
|
||||
std::string errMsg;
|
||||
struct addrinfo* res = dnsLookup->resolve(errMsg, [] { return false; });
|
||||
struct addrinfo* res = dnsLookup->resolve(errMsg,
|
||||
[]
|
||||
{
|
||||
return false;
|
||||
});
|
||||
std::cerr << "Error message: " << errMsg << std::endl;
|
||||
REQUIRE(res == nullptr);
|
||||
}
|
||||
@ -43,7 +46,11 @@ TEST_CASE("dns", "[net]")
|
||||
|
||||
std::string errMsg;
|
||||
// The callback returning true means we are requesting cancellation
|
||||
struct addrinfo* res = dnsLookup->resolve(errMsg, [] { return true; });
|
||||
struct addrinfo* res = dnsLookup->resolve(errMsg,
|
||||
[]
|
||||
{
|
||||
return true;
|
||||
});
|
||||
std::cerr << "Error message: " << errMsg << std::endl;
|
||||
REQUIRE(res == nullptr);
|
||||
}
|
||||
|
@ -5,11 +5,11 @@
|
||||
*/
|
||||
|
||||
#include "IXGetFreePort.h"
|
||||
|
||||
#include <ixwebsocket/IXNetSystem.h>
|
||||
#include <ixwebsocket/IXSocket.h>
|
||||
|
||||
#include <string>
|
||||
#include <random>
|
||||
#include <string>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
@ -30,8 +30,7 @@ namespace ix
|
||||
}
|
||||
|
||||
int enable = 1;
|
||||
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
|
||||
(char*) &enable, sizeof(enable)) < 0)
|
||||
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char*) &enable, sizeof(enable)) < 0)
|
||||
{
|
||||
return getAnyFreePortRandom();
|
||||
}
|
||||
@ -39,10 +38,10 @@ namespace ix
|
||||
// Bind to port 0. This is the standard way to get a free port.
|
||||
struct sockaddr_in server; // server address information
|
||||
server.sin_family = AF_INET;
|
||||
server.sin_port = htons(0);
|
||||
server.sin_port = htons(0);
|
||||
server.sin_addr.s_addr = inet_addr("127.0.0.1");
|
||||
|
||||
if (bind(sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)
|
||||
if (bind(sockfd, (struct sockaddr*) &server, sizeof(server)) < 0)
|
||||
{
|
||||
Socket::closeSocket(sockfd);
|
||||
return getAnyFreePortRandom();
|
||||
@ -50,7 +49,7 @@ namespace ix
|
||||
|
||||
struct sockaddr_in sa; // server address information
|
||||
socklen_t len = sizeof(sa);
|
||||
if (getsockname(sockfd, (struct sockaddr *) &sa, &len) < 0)
|
||||
if (getsockname(sockfd, (struct sockaddr*) &sa, &len) < 0)
|
||||
{
|
||||
Socket::closeSocket(sockfd);
|
||||
return getAnyFreePortRandom();
|
||||
@ -67,11 +66,11 @@ namespace ix
|
||||
while (true)
|
||||
{
|
||||
#if defined(__has_feature)
|
||||
# if __has_feature(address_sanitizer)
|
||||
#if __has_feature(address_sanitizer)
|
||||
int port = getAnyFreePortRandom();
|
||||
# else
|
||||
#else
|
||||
int port = getAnyFreePort();
|
||||
# endif
|
||||
#endif
|
||||
#else
|
||||
int port = getAnyFreePort();
|
||||
#endif
|
||||
|
@ -4,11 +4,10 @@
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "catch.hpp"
|
||||
#include <iostream>
|
||||
#include <ixwebsocket/IXHttpClient.h>
|
||||
|
||||
#include "catch.hpp"
|
||||
|
||||
using namespace ix;
|
||||
|
||||
TEST_CASE("http client", "[http]")
|
||||
@ -28,14 +27,10 @@ TEST_CASE("http client", "[http]")
|
||||
args->maxRedirects = 10;
|
||||
args->verbose = true;
|
||||
args->compress = true;
|
||||
args->logger = [](const std::string& msg)
|
||||
{
|
||||
std::cout << msg;
|
||||
};
|
||||
args->onProgressCallback = [](int current, int total) -> bool
|
||||
{
|
||||
std::cerr << "\r" << "Downloaded "
|
||||
<< current << " bytes out of " << total;
|
||||
args->logger = [](const std::string& msg) { std::cout << msg; };
|
||||
args->onProgressCallback = [](int current, int total) -> bool {
|
||||
std::cerr << "\r"
|
||||
<< "Downloaded " << current << " bytes out of " << total;
|
||||
return true;
|
||||
};
|
||||
|
||||
@ -70,14 +65,10 @@ TEST_CASE("http client", "[http]")
|
||||
args->maxRedirects = 10;
|
||||
args->verbose = true;
|
||||
args->compress = true;
|
||||
args->logger = [](const std::string& msg)
|
||||
{
|
||||
std::cout << msg;
|
||||
};
|
||||
args->onProgressCallback = [](int current, int total) -> bool
|
||||
{
|
||||
std::cerr << "\r" << "Downloaded "
|
||||
<< current << " bytes out of " << total;
|
||||
args->logger = [](const std::string& msg) { std::cout << msg; };
|
||||
args->onProgressCallback = [](int current, int total) -> bool {
|
||||
std::cerr << "\r"
|
||||
<< "Downloaded " << current << " bytes out of " << total;
|
||||
return true;
|
||||
};
|
||||
|
||||
@ -113,23 +104,18 @@ TEST_CASE("http client", "[http]")
|
||||
args->maxRedirects = 10;
|
||||
args->verbose = true;
|
||||
args->compress = true;
|
||||
args->logger = [](const std::string& msg)
|
||||
{
|
||||
std::cout << msg;
|
||||
};
|
||||
args->onProgressCallback = [](int current, int total) -> bool
|
||||
{
|
||||
std::cerr << "\r" << "Downloaded "
|
||||
<< current << " bytes out of " << total;
|
||||
args->logger = [](const std::string& msg) { std::cout << msg; };
|
||||
args->onProgressCallback = [](int current, int total) -> bool {
|
||||
std::cerr << "\r"
|
||||
<< "Downloaded " << current << " bytes out of " << total;
|
||||
return true;
|
||||
};
|
||||
|
||||
std::atomic<bool> requestCompleted(false);
|
||||
std::atomic<int> statusCode(0);
|
||||
|
||||
httpClient.performRequest(args, [&requestCompleted, &statusCode]
|
||||
(const HttpResponsePtr& response)
|
||||
{
|
||||
httpClient.performRequest(
|
||||
args, [&requestCompleted, &statusCode](const HttpResponsePtr& response) {
|
||||
std::cerr << "Upload size: " << response->uploadSize << std::endl;
|
||||
std::cerr << "Download size: " << response->downloadSize << std::endl;
|
||||
std::cerr << "Status: " << response->statusCode << std::endl;
|
||||
@ -138,8 +124,7 @@ TEST_CASE("http client", "[http]")
|
||||
// In case of failure, print response->errorMsg
|
||||
statusCode = response->statusCode;
|
||||
requestCompleted = true;
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
int wait = 0;
|
||||
while (wait < 5000)
|
||||
@ -171,14 +156,10 @@ TEST_CASE("http client", "[http]")
|
||||
args->maxRedirects = 10;
|
||||
args->verbose = true;
|
||||
args->compress = true;
|
||||
args->logger = [](const std::string& msg)
|
||||
{
|
||||
std::cout << msg;
|
||||
};
|
||||
args->onProgressCallback = [](int current, int total) -> bool
|
||||
{
|
||||
std::cerr << "\r" << "Downloaded "
|
||||
<< current << " bytes out of " << total;
|
||||
args->logger = [](const std::string& msg) { std::cout << msg; };
|
||||
args->onProgressCallback = [](int current, int total) -> bool {
|
||||
std::cerr << "\r"
|
||||
<< "Downloaded " << current << " bytes out of " << total;
|
||||
return true;
|
||||
};
|
||||
|
||||
@ -189,9 +170,10 @@ TEST_CASE("http client", "[http]")
|
||||
|
||||
for (int i = 0; i < 3; ++i)
|
||||
{
|
||||
httpClient.performRequest(args, [i, &requestCompleted, &statusCode0, &statusCode1, &statusCode2]
|
||||
(const HttpResponsePtr& response)
|
||||
{
|
||||
httpClient.performRequest(
|
||||
args,
|
||||
[i, &requestCompleted, &statusCode0, &statusCode1, &statusCode2](
|
||||
const HttpResponsePtr& response) {
|
||||
std::cerr << "Upload size: " << response->uploadSize << std::endl;
|
||||
std::cerr << "Download size: " << response->downloadSize << std::endl;
|
||||
std::cerr << "Status: " << response->statusCode << std::endl;
|
||||
@ -211,8 +193,7 @@ TEST_CASE("http client", "[http]")
|
||||
statusCode2 = response->statusCode;
|
||||
requestCompleted = true;
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
int wait = 0;
|
||||
|
@ -4,12 +4,11 @@
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXGetFreePort.h"
|
||||
#include "catch.hpp"
|
||||
#include <iostream>
|
||||
#include <ixwebsocket/IXHttpClient.h>
|
||||
#include <ixwebsocket/IXHttpServer.h>
|
||||
#include "IXGetFreePort.h"
|
||||
|
||||
#include "catch.hpp"
|
||||
|
||||
using namespace ix;
|
||||
|
||||
@ -39,14 +38,10 @@ TEST_CASE("http server", "[httpd]")
|
||||
args->maxRedirects = 10;
|
||||
args->verbose = true;
|
||||
args->compress = true;
|
||||
args->logger = [](const std::string& msg)
|
||||
{
|
||||
std::cout << msg;
|
||||
};
|
||||
args->onProgressCallback = [](int current, int total) -> bool
|
||||
{
|
||||
std::cerr << "\r" << "Downloaded "
|
||||
<< current << " bytes out of " << total;
|
||||
args->logger = [](const std::string& msg) { std::cout << msg; };
|
||||
args->onProgressCallback = [](int current, int total) -> bool {
|
||||
std::cerr << "\r"
|
||||
<< "Downloaded " << current << " bytes out of " << total;
|
||||
return true;
|
||||
};
|
||||
|
||||
|
@ -4,52 +4,50 @@
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "catch.hpp"
|
||||
#include <iostream>
|
||||
#include <ixwebsocket/IXHttp.h>
|
||||
|
||||
#include "catch.hpp"
|
||||
#include <string.h>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
|
||||
TEST_CASE("http", "[http]")
|
||||
{
|
||||
SECTION("Normal case")
|
||||
TEST_CASE("http", "[http]")
|
||||
{
|
||||
std::string line = "HTTP/1.1 200";
|
||||
auto result = Http::parseStatusLine(line);
|
||||
SECTION("Normal case")
|
||||
{
|
||||
std::string line = "HTTP/1.1 200";
|
||||
auto result = Http::parseStatusLine(line);
|
||||
|
||||
REQUIRE(result.first == "HTTP/1.1");
|
||||
REQUIRE(result.second == 200);
|
||||
REQUIRE(result.first == "HTTP/1.1");
|
||||
REQUIRE(result.second == 200);
|
||||
}
|
||||
|
||||
SECTION("http/1.0 case")
|
||||
{
|
||||
std::string line = "HTTP/1.0 200";
|
||||
auto result = Http::parseStatusLine(line);
|
||||
|
||||
REQUIRE(result.first == "HTTP/1.0");
|
||||
REQUIRE(result.second == 200);
|
||||
}
|
||||
|
||||
SECTION("empty case")
|
||||
{
|
||||
std::string line = "";
|
||||
auto result = Http::parseStatusLine(line);
|
||||
|
||||
REQUIRE(result.first == "");
|
||||
REQUIRE(result.second == -1);
|
||||
}
|
||||
|
||||
SECTION("empty case")
|
||||
{
|
||||
std::string line = "HTTP/1.1";
|
||||
auto result = Http::parseStatusLine(line);
|
||||
|
||||
REQUIRE(result.first == "HTTP/1.1");
|
||||
REQUIRE(result.second == -1);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("http/1.0 case")
|
||||
{
|
||||
std::string line = "HTTP/1.0 200";
|
||||
auto result = Http::parseStatusLine(line);
|
||||
|
||||
REQUIRE(result.first == "HTTP/1.0");
|
||||
REQUIRE(result.second == 200);
|
||||
}
|
||||
|
||||
SECTION("empty case")
|
||||
{
|
||||
std::string line = "";
|
||||
auto result = Http::parseStatusLine(line);
|
||||
|
||||
REQUIRE(result.first == "");
|
||||
REQUIRE(result.second == -1);
|
||||
}
|
||||
|
||||
SECTION("empty case")
|
||||
{
|
||||
std::string line = "HTTP/1.1";
|
||||
auto result = Http::parseStatusLine(line);
|
||||
|
||||
REQUIRE(result.first == "HTTP/1.1");
|
||||
REQUIRE(result.second == -1);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace ix
|
||||
|
@ -4,11 +4,10 @@
|
||||
* Copyright (c) 2018 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "catch.hpp"
|
||||
|
||||
#include "IXTest.h"
|
||||
#include <ixwebsocket/IXSocketConnect.h>
|
||||
#include "catch.hpp"
|
||||
#include <iostream>
|
||||
#include <ixwebsocket/IXSocketConnect.h>
|
||||
|
||||
using namespace ix;
|
||||
|
||||
|
@ -4,13 +4,12 @@
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
#include <ixwebsocket/IXSocketFactory.h>
|
||||
#include <ixwebsocket/IXSocket.h>
|
||||
#include <ixwebsocket/IXCancellationRequest.h>
|
||||
|
||||
#include "IXTest.h"
|
||||
#include "catch.hpp"
|
||||
#include <iostream>
|
||||
#include <ixwebsocket/IXCancellationRequest.h>
|
||||
#include <ixwebsocket/IXSocket.h>
|
||||
#include <ixwebsocket/IXSocketFactory.h>
|
||||
#include <string.h>
|
||||
|
||||
using namespace ix;
|
||||
@ -33,8 +32,7 @@ namespace ix
|
||||
Logger() << "errMsg: " << errMsg;
|
||||
REQUIRE(success);
|
||||
|
||||
Logger() << "Sending request: " << request
|
||||
<< "to " << host << ":" << port;
|
||||
Logger() << "Sending request: " << request << "to " << host << ":" << port;
|
||||
REQUIRE(socket->writeBytes(request, isCancellationRequested));
|
||||
|
||||
auto lineResult = socket->readLine(isCancellationRequested);
|
||||
@ -49,11 +47,12 @@ namespace ix
|
||||
REQUIRE(sscanf(line.c_str(), "HTTP/1.1 %d", &status) == 1);
|
||||
REQUIRE(status == expectedStatus);
|
||||
}
|
||||
}
|
||||
} // namespace ix
|
||||
|
||||
TEST_CASE("socket", "[socket]")
|
||||
{
|
||||
SECTION("Connect to a local websocket server over a free port. Send GET request without header. Should return 400")
|
||||
SECTION("Connect to a local websocket server over a free port. Send GET request without "
|
||||
"header. Should return 400")
|
||||
{
|
||||
// Start a server first which we'll hit with our socket code
|
||||
int port = getFreePort();
|
||||
@ -78,7 +77,8 @@ TEST_CASE("socket", "[socket]")
|
||||
}
|
||||
|
||||
#if defined(IXWEBSOCKET_USE_TLS)
|
||||
SECTION("Connect to google HTTPS server over port 443. Send GET request without header. Should return 200")
|
||||
SECTION("Connect to google HTTPS server over port 443. Send GET request without header. Should "
|
||||
"return 200")
|
||||
{
|
||||
std::string errMsg;
|
||||
bool tls = true;
|
||||
|
100
test/IXTest.cpp
100
test/IXTest.cpp
@ -5,19 +5,19 @@
|
||||
*/
|
||||
|
||||
#include "IXTest.h"
|
||||
#include <ixwebsocket/IXWebSocket.h>
|
||||
#include <ixwebsocket/IXNetSystem.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <stdlib.h>
|
||||
#include <stack>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <ixwebsocket/IXNetSystem.h>
|
||||
#include <ixwebsocket/IXWebSocket.h>
|
||||
#include <mutex>
|
||||
#include <random>
|
||||
#include <stack>
|
||||
#include <stdlib.h>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
|
||||
namespace ix
|
||||
@ -29,19 +29,16 @@ namespace ix
|
||||
|
||||
void setupWebSocketTrafficTrackerCallback()
|
||||
{
|
||||
ix::WebSocket::setTrafficTrackerCallback(
|
||||
[](size_t size, bool incoming)
|
||||
ix::WebSocket::setTrafficTrackerCallback([](size_t size, bool incoming) {
|
||||
if (incoming)
|
||||
{
|
||||
if (incoming)
|
||||
{
|
||||
incomingBytes += size;
|
||||
}
|
||||
else
|
||||
{
|
||||
outgoingBytes += size;
|
||||
}
|
||||
incomingBytes += size;
|
||||
}
|
||||
);
|
||||
else
|
||||
{
|
||||
outgoingBytes += size;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void reportWebSocketTraffic()
|
||||
@ -61,8 +58,7 @@ namespace ix
|
||||
{
|
||||
auto now = std::chrono::system_clock::now();
|
||||
auto seconds =
|
||||
std::chrono::duration_cast<std::chrono::seconds>(
|
||||
now.time_since_epoch()).count();
|
||||
std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
|
||||
|
||||
return std::to_string(seconds);
|
||||
}
|
||||
@ -72,18 +68,15 @@ namespace ix
|
||||
Logger() << msg;
|
||||
}
|
||||
|
||||
void hexDump(const std::string& prefix,
|
||||
const std::string& s)
|
||||
void hexDump(const std::string& prefix, const std::string& s)
|
||||
{
|
||||
std::ostringstream ss;
|
||||
bool upper_case = false;
|
||||
|
||||
for (std::string::size_type i = 0; i < s.length(); ++i)
|
||||
{
|
||||
ss << std::hex
|
||||
<< std::setfill('0')
|
||||
<< std::setw(2)
|
||||
<< (upper_case ? std::uppercase : std::nouppercase) << (int)s[i];
|
||||
ss << std::hex << std::setfill('0') << std::setw(2)
|
||||
<< (upper_case ? std::uppercase : std::nouppercase) << (int) s[i];
|
||||
}
|
||||
|
||||
std::cout << prefix << ": " << s << " => " << ss.str() << std::endl;
|
||||
@ -91,41 +84,36 @@ namespace ix
|
||||
|
||||
bool startWebSocketEchoServer(ix::WebSocketServer& server)
|
||||
{
|
||||
server.setOnConnectionCallback(
|
||||
[&server](std::shared_ptr<ix::WebSocket> webSocket,
|
||||
std::shared_ptr<ConnectionState> connectionState)
|
||||
{
|
||||
webSocket->setOnMessageCallback(
|
||||
[webSocket, connectionState, &server](const ix::WebSocketMessagePtr& msg)
|
||||
server.setOnConnectionCallback([&server](std::shared_ptr<ix::WebSocket> webSocket,
|
||||
std::shared_ptr<ConnectionState> connectionState) {
|
||||
webSocket->setOnMessageCallback(
|
||||
[webSocket, connectionState, &server](const ix::WebSocketMessagePtr& msg) {
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
Logger() << "New connection";
|
||||
Logger() << "Uri: " << msg->openInfo.uri;
|
||||
Logger() << "Headers:";
|
||||
for (auto it : msg->openInfo.headers)
|
||||
{
|
||||
Logger() << "New connection";
|
||||
Logger() << "Uri: " << msg->openInfo.uri;
|
||||
Logger() << "Headers:";
|
||||
for (auto it : msg->openInfo.headers)
|
||||
{
|
||||
Logger() << it.first << ": " << it.second;
|
||||
}
|
||||
Logger() << it.first << ": " << it.second;
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
Logger() << "Closed connection";
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
for (auto&& client : server.getClients())
|
||||
{
|
||||
Logger() << "Closed connection";
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
for (auto&& client : server.getClients())
|
||||
if (client != webSocket)
|
||||
{
|
||||
if (client != webSocket)
|
||||
{
|
||||
client->send(msg->str, msg->binary);
|
||||
}
|
||||
client->send(msg->str, msg->binary);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
auto res = server.listen();
|
||||
if (!res.first)
|
||||
@ -150,7 +138,7 @@ namespace ix
|
||||
file.seekg(0, file.beg);
|
||||
|
||||
memblock.resize((size_t) size);
|
||||
file.read((char*)&memblock.front(), static_cast<std::streamsize>(size));
|
||||
file.read((char*) &memblock.front(), static_cast<std::streamsize>(size));
|
||||
|
||||
return memblock;
|
||||
}
|
||||
@ -190,4 +178,4 @@ namespace ix
|
||||
|
||||
return appConfig;
|
||||
}
|
||||
}
|
||||
} // namespace ix
|
||||
|
@ -6,10 +6,10 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "IXAppConfig.h"
|
||||
#include "IXGetFreePort.h"
|
||||
#include <iostream>
|
||||
#include <ixwebsocket/IXWebSocketServer.h>
|
||||
#include "IXAppConfig.h"
|
||||
#include <mutex>
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <sstream>
|
||||
|
@ -4,6 +4,7 @@
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "catch.hpp"
|
||||
#include <ixwebsocket/IXCancellationRequest.h>
|
||||
#include <ixwebsocket/IXConnectionState.h>
|
||||
#include <ixwebsocket/IXDNSLookup.h>
|
||||
@ -39,8 +40,6 @@
|
||||
#include <ixwebsocket/LUrlParser.h>
|
||||
#include <ixwebsocket/libwshandshake.hpp>
|
||||
|
||||
#include "catch.hpp"
|
||||
|
||||
using namespace ix;
|
||||
|
||||
TEST_CASE("unity build", "[unity_build]")
|
||||
|
@ -4,105 +4,115 @@
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
#include <ixwebsocket/IXUrlParser.h>
|
||||
|
||||
#include "IXTest.h"
|
||||
#include "catch.hpp"
|
||||
#include <iostream>
|
||||
#include <ixwebsocket/IXUrlParser.h>
|
||||
#include <string.h>
|
||||
|
||||
using namespace ix;
|
||||
|
||||
namespace ix
|
||||
{
|
||||
|
||||
TEST_CASE("urlParser", "[urlParser]")
|
||||
{
|
||||
SECTION("http://google.com")
|
||||
TEST_CASE("urlParser", "[urlParser]")
|
||||
{
|
||||
std::string url = "http://google.com";
|
||||
std::string protocol, host, path, query;
|
||||
int port;
|
||||
bool res;
|
||||
SECTION("http://google.com")
|
||||
{
|
||||
std::string url = "http://google.com";
|
||||
std::string protocol, host, path, query;
|
||||
int port;
|
||||
bool res;
|
||||
|
||||
res = UrlParser::parse(url, protocol, host, path, query, port);
|
||||
res = UrlParser::parse(url, protocol, host, path, query, port);
|
||||
|
||||
REQUIRE(res);
|
||||
REQUIRE(protocol == "http");
|
||||
REQUIRE(host == "google.com");
|
||||
REQUIRE(path == "/");
|
||||
REQUIRE(query == "");
|
||||
REQUIRE(port == 80); // default port for http
|
||||
REQUIRE(res);
|
||||
REQUIRE(protocol == "http");
|
||||
REQUIRE(host == "google.com");
|
||||
REQUIRE(path == "/");
|
||||
REQUIRE(query == "");
|
||||
REQUIRE(port == 80); // default port for http
|
||||
}
|
||||
|
||||
SECTION("https://google.com")
|
||||
{
|
||||
std::string url = "https://google.com";
|
||||
std::string protocol, host, path, query;
|
||||
int port;
|
||||
bool res;
|
||||
|
||||
res = UrlParser::parse(url, protocol, host, path, query, port);
|
||||
|
||||
REQUIRE(res);
|
||||
REQUIRE(protocol == "https");
|
||||
REQUIRE(host == "google.com");
|
||||
REQUIRE(path == "/");
|
||||
REQUIRE(query == "");
|
||||
REQUIRE(port == 443); // default port for https
|
||||
}
|
||||
|
||||
SECTION("ws://google.com")
|
||||
{
|
||||
std::string url = "ws://google.com";
|
||||
std::string protocol, host, path, query;
|
||||
int port;
|
||||
bool res;
|
||||
|
||||
res = UrlParser::parse(url, protocol, host, path, query, port);
|
||||
|
||||
REQUIRE(res);
|
||||
REQUIRE(protocol == "ws");
|
||||
REQUIRE(host == "google.com");
|
||||
REQUIRE(path == "/");
|
||||
REQUIRE(query == "");
|
||||
REQUIRE(port == 80); // default port for ws
|
||||
}
|
||||
|
||||
SECTION("wss://google.com/ws?arg=value")
|
||||
{
|
||||
std::string url = "wss://google.com/ws?arg=value&arg2=value2";
|
||||
std::string protocol, host, path, query;
|
||||
int port;
|
||||
bool res;
|
||||
|
||||
res = UrlParser::parse(url, protocol, host, path, query, port);
|
||||
|
||||
REQUIRE(res);
|
||||
REQUIRE(protocol == "wss");
|
||||
REQUIRE(host == "google.com");
|
||||
REQUIRE(path == "/ws?arg=value&arg2=value2");
|
||||
REQUIRE(query == "arg=value&arg2=value2");
|
||||
REQUIRE(port == 443); // default port for wss
|
||||
}
|
||||
|
||||
SECTION("real test")
|
||||
{
|
||||
std::string url =
|
||||
"ws://127.0.0.1:7350/"
|
||||
"ws?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
|
||||
"eyJleHAiOjE1NTcxNzAwNzIsInVpZCI6ImMwZmZjOGE1LTk4OTktNDAwYi1hNGU5LTJjNWM3NjFmNWQxZi"
|
||||
"IsInVzbiI6InN2YmhOdlNJSmEifQ.5L8BUbpTA4XAHlSrdwhIVlrlIpRtjExepim7Yh5eEO4&status="
|
||||
"true&format=protobuf";
|
||||
std::string protocol, host, path, query;
|
||||
int port;
|
||||
bool res;
|
||||
|
||||
res = UrlParser::parse(url, protocol, host, path, query, port);
|
||||
|
||||
REQUIRE(res);
|
||||
REQUIRE(protocol == "ws");
|
||||
REQUIRE(host == "127.0.0.1");
|
||||
REQUIRE(path ==
|
||||
"/ws?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
|
||||
"eyJleHAiOjE1NTcxNzAwNzIsInVpZCI6ImMwZmZjOGE1LTk4OTktNDAwYi1hNGU5LTJjNWM3NjFmNW"
|
||||
"QxZiIsInVzbiI6InN2YmhOdlNJSmEifQ.5L8BUbpTA4XAHlSrdwhIVlrlIpRtjExepim7Yh5eEO4&"
|
||||
"status=true&format=protobuf");
|
||||
REQUIRE(query ==
|
||||
"token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
|
||||
"eyJleHAiOjE1NTcxNzAwNzIsInVpZCI6ImMwZmZjOGE1LTk4OTktNDAwYi1hNGU5LTJjNWM3NjFmNW"
|
||||
"QxZiIsInVzbiI6InN2YmhOdlNJSmEifQ.5L8BUbpTA4XAHlSrdwhIVlrlIpRtjExepim7Yh5eEO4&"
|
||||
"status=true&format=protobuf");
|
||||
REQUIRE(port == 7350);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("https://google.com")
|
||||
{
|
||||
std::string url = "https://google.com";
|
||||
std::string protocol, host, path, query;
|
||||
int port;
|
||||
bool res;
|
||||
|
||||
res = UrlParser::parse(url, protocol, host, path, query, port);
|
||||
|
||||
REQUIRE(res);
|
||||
REQUIRE(protocol == "https");
|
||||
REQUIRE(host == "google.com");
|
||||
REQUIRE(path == "/");
|
||||
REQUIRE(query == "");
|
||||
REQUIRE(port == 443); // default port for https
|
||||
}
|
||||
|
||||
SECTION("ws://google.com")
|
||||
{
|
||||
std::string url = "ws://google.com";
|
||||
std::string protocol, host, path, query;
|
||||
int port;
|
||||
bool res;
|
||||
|
||||
res = UrlParser::parse(url, protocol, host, path, query, port);
|
||||
|
||||
REQUIRE(res);
|
||||
REQUIRE(protocol == "ws");
|
||||
REQUIRE(host == "google.com");
|
||||
REQUIRE(path == "/");
|
||||
REQUIRE(query == "");
|
||||
REQUIRE(port == 80); // default port for ws
|
||||
}
|
||||
|
||||
SECTION("wss://google.com/ws?arg=value")
|
||||
{
|
||||
std::string url = "wss://google.com/ws?arg=value&arg2=value2";
|
||||
std::string protocol, host, path, query;
|
||||
int port;
|
||||
bool res;
|
||||
|
||||
res = UrlParser::parse(url, protocol, host, path, query, port);
|
||||
|
||||
REQUIRE(res);
|
||||
REQUIRE(protocol == "wss");
|
||||
REQUIRE(host == "google.com");
|
||||
REQUIRE(path == "/ws?arg=value&arg2=value2");
|
||||
REQUIRE(query == "arg=value&arg2=value2");
|
||||
REQUIRE(port == 443); // default port for wss
|
||||
}
|
||||
|
||||
SECTION("real test")
|
||||
{
|
||||
std::string url = "ws://127.0.0.1:7350/ws?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NTcxNzAwNzIsInVpZCI6ImMwZmZjOGE1LTk4OTktNDAwYi1hNGU5LTJjNWM3NjFmNWQxZiIsInVzbiI6InN2YmhOdlNJSmEifQ.5L8BUbpTA4XAHlSrdwhIVlrlIpRtjExepim7Yh5eEO4&status=true&format=protobuf";
|
||||
std::string protocol, host, path, query;
|
||||
int port;
|
||||
bool res;
|
||||
|
||||
res = UrlParser::parse(url, protocol, host, path, query, port);
|
||||
|
||||
REQUIRE(res);
|
||||
REQUIRE(protocol == "ws");
|
||||
REQUIRE(host == "127.0.0.1");
|
||||
REQUIRE(path == "/ws?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NTcxNzAwNzIsInVpZCI6ImMwZmZjOGE1LTk4OTktNDAwYi1hNGU5LTJjNWM3NjFmNWQxZiIsInVzbiI6InN2YmhOdlNJSmEifQ.5L8BUbpTA4XAHlSrdwhIVlrlIpRtjExepim7Yh5eEO4&status=true&format=protobuf");
|
||||
REQUIRE(query == "token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NTcxNzAwNzIsInVpZCI6ImMwZmZjOGE1LTk4OTktNDAwYi1hNGU5LTJjNWM3NjFmNWQxZiIsInVzbiI6InN2YmhOdlNJSmEifQ.5L8BUbpTA4XAHlSrdwhIVlrlIpRtjExepim7Yh5eEO4&status=true&format=protobuf");
|
||||
REQUIRE(port == 7350);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace ix
|
||||
|
@ -9,17 +9,15 @@
|
||||
// websocket_chat_server/broacast-server.js
|
||||
//
|
||||
|
||||
#include "IXTest.h"
|
||||
#include "catch.hpp"
|
||||
#include "msgpack11.hpp"
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
#include <mutex>
|
||||
#include <ixwebsocket/IXWebSocket.h>
|
||||
#include <ixwebsocket/IXWebSocketServer.h>
|
||||
#include "msgpack11.hpp"
|
||||
|
||||
#include "IXTest.h"
|
||||
|
||||
#include "catch.hpp"
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
using msgpack11::MsgPack;
|
||||
using namespace ix;
|
||||
@ -28,41 +26,37 @@ namespace
|
||||
{
|
||||
class WebSocketChat
|
||||
{
|
||||
public:
|
||||
WebSocketChat(const std::string& user,
|
||||
const std::string& session,
|
||||
int port);
|
||||
public:
|
||||
WebSocketChat(const std::string& user, const std::string& session, int port);
|
||||
|
||||
void subscribe(const std::string& channel);
|
||||
void start();
|
||||
void stop();
|
||||
bool isReady() const;
|
||||
void subscribe(const std::string& channel);
|
||||
void start();
|
||||
void stop();
|
||||
bool isReady() const;
|
||||
|
||||
void sendMessage(const std::string& text);
|
||||
size_t getReceivedMessagesCount() const;
|
||||
const std::vector<std::string>& getReceivedMessages() const;
|
||||
void sendMessage(const std::string& text);
|
||||
size_t getReceivedMessagesCount() const;
|
||||
const std::vector<std::string>& getReceivedMessages() const;
|
||||
|
||||
std::string encodeMessage(const std::string& text);
|
||||
std::pair<std::string, std::string> decodeMessage(const std::string& str);
|
||||
void appendMessage(const std::string& message);
|
||||
std::string encodeMessage(const std::string& text);
|
||||
std::pair<std::string, std::string> decodeMessage(const std::string& str);
|
||||
void appendMessage(const std::string& message);
|
||||
|
||||
private:
|
||||
std::string _user;
|
||||
std::string _session;
|
||||
int _port;
|
||||
private:
|
||||
std::string _user;
|
||||
std::string _session;
|
||||
int _port;
|
||||
|
||||
ix::WebSocket _webSocket;
|
||||
ix::WebSocket _webSocket;
|
||||
|
||||
std::vector<std::string> _receivedMessages;
|
||||
mutable std::mutex _mutex;
|
||||
std::vector<std::string> _receivedMessages;
|
||||
mutable std::mutex _mutex;
|
||||
};
|
||||
|
||||
WebSocketChat::WebSocketChat(const std::string& user,
|
||||
const std::string& session,
|
||||
int port) :
|
||||
_user(user),
|
||||
_session(session),
|
||||
_port(port)
|
||||
WebSocketChat::WebSocketChat(const std::string& user, const std::string& session, int port)
|
||||
: _user(user)
|
||||
, _session(session)
|
||||
, _port(port)
|
||||
{
|
||||
;
|
||||
}
|
||||
@ -100,10 +94,7 @@ namespace
|
||||
std::string url;
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "ws://127.0.0.1:"
|
||||
<< _port
|
||||
<< "/"
|
||||
<< _user;
|
||||
ss << "ws://127.0.0.1:" << _port << "/" << _user;
|
||||
|
||||
url = ss.str();
|
||||
}
|
||||
@ -113,70 +104,61 @@ namespace
|
||||
std::stringstream ss;
|
||||
log(std::string("Connecting to url: ") + url);
|
||||
|
||||
_webSocket.setOnMessageCallback(
|
||||
[this](const ix::WebSocketMessagePtr& msg)
|
||||
_webSocket.setOnMessageCallback([this](const ix::WebSocketMessagePtr& msg) {
|
||||
std::stringstream ss;
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
std::stringstream ss;
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
ss << "cmd_websocket_chat: user "
|
||||
<< _user
|
||||
<< " Connected !";
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
ss << "cmd_websocket_chat: user "
|
||||
<< _user
|
||||
<< " disconnected !";
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
auto result = decodeMessage(msg->str);
|
||||
ss << "cmd_websocket_chat: user " << _user << " Connected !";
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
ss << "cmd_websocket_chat: user " << _user << " disconnected !";
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
auto result = decodeMessage(msg->str);
|
||||
|
||||
// Our "chat" / "broacast" node.js server does not send us
|
||||
// the messages we send, so we don't need to have a msg_user != user
|
||||
// as we do for the satori chat example.
|
||||
// Our "chat" / "broacast" node.js server does not send us
|
||||
// the messages we send, so we don't need to have a msg_user != user
|
||||
// as we do for the satori chat example.
|
||||
|
||||
// store text
|
||||
appendMessage(result.second);
|
||||
// store text
|
||||
appendMessage(result.second);
|
||||
|
||||
std::string payload = result.second;
|
||||
if (payload.size() > 2000)
|
||||
{
|
||||
payload = "<message too large>";
|
||||
}
|
||||
std::string payload = result.second;
|
||||
if (payload.size() > 2000)
|
||||
{
|
||||
payload = "<message too large>";
|
||||
}
|
||||
|
||||
ss << std::endl
|
||||
<< result.first << " > " << payload
|
||||
<< std::endl
|
||||
<< _user << " > ";
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Error)
|
||||
{
|
||||
ss << "cmd_websocket_chat: Error ! " << msg->errorInfo.reason;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Ping)
|
||||
{
|
||||
log("cmd_websocket_chat: received ping message");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Pong)
|
||||
{
|
||||
log("cmd_websocket_chat: received pong message");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Fragment)
|
||||
{
|
||||
log("cmd_websocket_chat: received message fragment");
|
||||
}
|
||||
else
|
||||
{
|
||||
ss << "Unexpected ix::WebSocketMessageType";
|
||||
log(ss.str());
|
||||
}
|
||||
});
|
||||
ss << std::endl << result.first << " > " << payload << std::endl << _user << " > ";
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Error)
|
||||
{
|
||||
ss << "cmd_websocket_chat: Error ! " << msg->errorInfo.reason;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Ping)
|
||||
{
|
||||
log("cmd_websocket_chat: received ping message");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Pong)
|
||||
{
|
||||
log("cmd_websocket_chat: received pong message");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Fragment)
|
||||
{
|
||||
log("cmd_websocket_chat: received message fragment");
|
||||
}
|
||||
else
|
||||
{
|
||||
ss << "Unexpected ix::WebSocketMessageType";
|
||||
log(ss.str());
|
||||
}
|
||||
});
|
||||
|
||||
_webSocket.start();
|
||||
}
|
||||
@ -211,42 +193,37 @@ namespace
|
||||
|
||||
bool startServer(ix::WebSocketServer& server)
|
||||
{
|
||||
server.setOnConnectionCallback(
|
||||
[&server](std::shared_ptr<ix::WebSocket> webSocket,
|
||||
std::shared_ptr<ConnectionState> connectionState)
|
||||
{
|
||||
webSocket->setOnMessageCallback(
|
||||
[webSocket, connectionState, &server](const ix::WebSocketMessagePtr& msg)
|
||||
server.setOnConnectionCallback([&server](std::shared_ptr<ix::WebSocket> webSocket,
|
||||
std::shared_ptr<ConnectionState> connectionState) {
|
||||
webSocket->setOnMessageCallback(
|
||||
[webSocket, connectionState, &server](const ix::WebSocketMessagePtr& msg) {
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
Logger() << "New connection";
|
||||
Logger() << "id: " << connectionState->getId();
|
||||
Logger() << "Uri: " << msg->openInfo.uri;
|
||||
Logger() << "Headers:";
|
||||
for (auto it : msg->openInfo.headers)
|
||||
{
|
||||
Logger() << "New connection";
|
||||
Logger() << "id: " << connectionState->getId();
|
||||
Logger() << "Uri: " << msg->openInfo.uri;
|
||||
Logger() << "Headers:";
|
||||
for (auto it : msg->openInfo.headers)
|
||||
{
|
||||
Logger() << it.first << ": " << it.second;
|
||||
}
|
||||
Logger() << it.first << ": " << it.second;
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
log("Closed connection");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
for (auto&& client : server.getClients())
|
||||
{
|
||||
log("Closed connection");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
for (auto&& client : server.getClients())
|
||||
if (client != webSocket)
|
||||
{
|
||||
if (client != webSocket)
|
||||
{
|
||||
client->sendBinary(msg->str);
|
||||
}
|
||||
client->sendBinary(msg->str);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
auto res = server.listen();
|
||||
if (!res.first)
|
||||
@ -258,7 +235,7 @@ namespace
|
||||
server.start();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Websocket_chat", "[websocket_chat]")
|
||||
{
|
||||
@ -305,8 +282,7 @@ TEST_CASE("Websocket_chat", "[websocket_chat]")
|
||||
|
||||
// Wait until all messages are received. 10s timeout
|
||||
int attempts = 0;
|
||||
while (chatA.getReceivedMessagesCount() != 3 ||
|
||||
chatB.getReceivedMessagesCount() != 3)
|
||||
while (chatA.getReceivedMessagesCount() != 3 || chatB.getReceivedMessagesCount() != 3)
|
||||
{
|
||||
REQUIRE(attempts++ < 10);
|
||||
ix::msleep(1000);
|
||||
|
@ -4,15 +4,13 @@
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXTest.h"
|
||||
#include "catch.hpp"
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <queue>
|
||||
#include <ixwebsocket/IXWebSocket.h>
|
||||
#include <ixwebsocket/IXWebSocketServer.h>
|
||||
|
||||
#include "IXTest.h"
|
||||
|
||||
#include "catch.hpp"
|
||||
#include <queue>
|
||||
#include <sstream>
|
||||
|
||||
using namespace ix;
|
||||
|
||||
@ -20,30 +18,30 @@ namespace
|
||||
{
|
||||
class WebSocketClient
|
||||
{
|
||||
public:
|
||||
WebSocketClient(int port);
|
||||
public:
|
||||
WebSocketClient(int port);
|
||||
|
||||
void subscribe(const std::string& channel);
|
||||
void start();
|
||||
void stop();
|
||||
void stop(uint16_t code, const std::string& reason);
|
||||
bool isReady() const;
|
||||
void subscribe(const std::string& channel);
|
||||
void start();
|
||||
void stop();
|
||||
void stop(uint16_t code, const std::string& reason);
|
||||
bool isReady() const;
|
||||
|
||||
uint16_t getCloseCode();
|
||||
const std::string& getCloseReason();
|
||||
bool getCloseRemote();
|
||||
uint16_t getCloseCode();
|
||||
const std::string& getCloseReason();
|
||||
bool getCloseRemote();
|
||||
|
||||
bool hasConnectionError() const;
|
||||
bool hasConnectionError() const;
|
||||
|
||||
private:
|
||||
ix::WebSocket _webSocket;
|
||||
int _port;
|
||||
private:
|
||||
ix::WebSocket _webSocket;
|
||||
int _port;
|
||||
|
||||
mutable std::mutex _mutexCloseData;
|
||||
uint16_t _closeCode;
|
||||
std::string _closeReason;
|
||||
bool _closeRemote;
|
||||
std::atomic<bool> _connectionError;
|
||||
mutable std::mutex _mutexCloseData;
|
||||
uint16_t _closeCode;
|
||||
std::string _closeReason;
|
||||
bool _closeRemote;
|
||||
std::atomic<bool> _connectionError;
|
||||
};
|
||||
|
||||
WebSocketClient::WebSocketClient(int port)
|
||||
@ -102,9 +100,7 @@ namespace
|
||||
std::string url;
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "ws://localhost:"
|
||||
<< _port
|
||||
<< "/";
|
||||
ss << "ws://localhost:" << _port << "/";
|
||||
|
||||
url = ss.str();
|
||||
}
|
||||
@ -115,57 +111,52 @@ namespace
|
||||
std::stringstream ss;
|
||||
log(std::string("Connecting to url: ") + url);
|
||||
|
||||
_webSocket.setOnMessageCallback(
|
||||
[this](const ix::WebSocketMessagePtr& msg)
|
||||
_webSocket.setOnMessageCallback([this](const ix::WebSocketMessagePtr& msg) {
|
||||
std::stringstream ss;
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
log("client connected");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
std::stringstream ss;
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
log("client connected");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "client disconnected("
|
||||
<< msg->closeInfo.code
|
||||
<< ","
|
||||
<< msg->closeInfo.reason
|
||||
<< ")";
|
||||
log(ss.str());
|
||||
ss << "client disconnected(" << msg->closeInfo.code << "," << msg->closeInfo.reason
|
||||
<< ")";
|
||||
log(ss.str());
|
||||
|
||||
std::lock_guard<std::mutex> lck(_mutexCloseData);
|
||||
std::lock_guard<std::mutex> lck(_mutexCloseData);
|
||||
|
||||
_closeCode = msg->closeInfo.code;
|
||||
_closeReason = std::string(msg->closeInfo.reason);
|
||||
_closeRemote = msg->closeInfo.remote;
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Error)
|
||||
{
|
||||
_connectionError = true;
|
||||
ss << "Error ! " << msg->errorInfo.reason;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Pong)
|
||||
{
|
||||
ss << "Received pong message " << msg->str;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Ping)
|
||||
{
|
||||
ss << "Received ping message " << msg->str;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
ss << "Received message " << msg->str;
|
||||
log(ss.str());
|
||||
}
|
||||
else
|
||||
{
|
||||
ss << "Invalid ix::WebSocketMessageType";
|
||||
log(ss.str());
|
||||
}
|
||||
});
|
||||
_closeCode = msg->closeInfo.code;
|
||||
_closeReason = std::string(msg->closeInfo.reason);
|
||||
_closeRemote = msg->closeInfo.remote;
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Error)
|
||||
{
|
||||
_connectionError = true;
|
||||
ss << "Error ! " << msg->errorInfo.reason;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Pong)
|
||||
{
|
||||
ss << "Received pong message " << msg->str;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Ping)
|
||||
{
|
||||
ss << "Received ping message " << msg->str;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
ss << "Received message " << msg->str;
|
||||
log(ss.str());
|
||||
}
|
||||
else
|
||||
{
|
||||
ss << "Invalid ix::WebSocketMessageType";
|
||||
log(ss.str());
|
||||
}
|
||||
});
|
||||
|
||||
_webSocket.start();
|
||||
}
|
||||
@ -178,43 +169,41 @@ namespace
|
||||
{
|
||||
// A dev/null server
|
||||
server.setOnConnectionCallback(
|
||||
[&receivedCloseCode, &receivedCloseReason, &receivedCloseRemote, &mutexWrite](std::shared_ptr<ix::WebSocket> webSocket,
|
||||
std::shared_ptr<ConnectionState> connectionState)
|
||||
{
|
||||
webSocket->setOnMessageCallback(
|
||||
[webSocket, connectionState, &receivedCloseCode, &receivedCloseReason, &receivedCloseRemote, &mutexWrite](const ix::WebSocketMessagePtr& msg)
|
||||
[&receivedCloseCode, &receivedCloseReason, &receivedCloseRemote, &mutexWrite](
|
||||
std::shared_ptr<ix::WebSocket> webSocket,
|
||||
std::shared_ptr<ConnectionState> connectionState) {
|
||||
webSocket->setOnMessageCallback([webSocket,
|
||||
connectionState,
|
||||
&receivedCloseCode,
|
||||
&receivedCloseReason,
|
||||
&receivedCloseRemote,
|
||||
&mutexWrite](const ix::WebSocketMessagePtr& msg) {
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
Logger() << "New server connection";
|
||||
Logger() << "id: " << connectionState->getId();
|
||||
Logger() << "Uri: " << msg->openInfo.uri;
|
||||
Logger() << "Headers:";
|
||||
for (auto it : msg->openInfo.headers)
|
||||
{
|
||||
Logger() << "New server connection";
|
||||
Logger() << "id: " << connectionState->getId();
|
||||
Logger() << "Uri: " << msg->openInfo.uri;
|
||||
Logger() << "Headers:";
|
||||
for (auto it : msg->openInfo.headers)
|
||||
{
|
||||
Logger() << it.first << ": " << it.second;
|
||||
}
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "Server closed connection("
|
||||
<< msg->closeInfo.code
|
||||
<< ","
|
||||
<< msg->closeInfo.reason
|
||||
<< ")";
|
||||
log(ss.str());
|
||||
|
||||
std::lock_guard<std::mutex> lck(mutexWrite);
|
||||
|
||||
receivedCloseCode = msg->closeInfo.code;
|
||||
receivedCloseReason = std::string(msg->closeInfo.reason);
|
||||
receivedCloseRemote = msg->closeInfo.remote;
|
||||
Logger() << it.first << ": " << it.second;
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
);
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "Server closed connection(" << msg->closeInfo.code << ","
|
||||
<< msg->closeInfo.reason << ")";
|
||||
log(ss.str());
|
||||
|
||||
std::lock_guard<std::mutex> lck(mutexWrite);
|
||||
|
||||
receivedCloseCode = msg->closeInfo.code;
|
||||
receivedCloseReason = std::string(msg->closeInfo.reason);
|
||||
receivedCloseRemote = msg->closeInfo.remote;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
auto res = server.listen();
|
||||
if (!res.first)
|
||||
@ -226,7 +215,7 @@ namespace
|
||||
server.start();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Websocket_client_close_default", "[close]")
|
||||
{
|
||||
@ -242,7 +231,11 @@ TEST_CASE("Websocket_client_close_default", "[close]")
|
||||
std::string serverReceivedCloseReason("");
|
||||
std::mutex mutexWrite;
|
||||
|
||||
REQUIRE(startServer(server, serverReceivedCloseCode, serverReceivedCloseReason, serverReceivedCloseRemote, mutexWrite));
|
||||
REQUIRE(startServer(server,
|
||||
serverReceivedCloseCode,
|
||||
serverReceivedCloseReason,
|
||||
serverReceivedCloseRemote,
|
||||
mutexWrite));
|
||||
|
||||
std::string session = ix::generateSessionId();
|
||||
WebSocketClient webSocketClient(port);
|
||||
@ -301,7 +294,11 @@ TEST_CASE("Websocket_client_close_params_given", "[close]")
|
||||
std::string serverReceivedCloseReason("");
|
||||
std::mutex mutexWrite;
|
||||
|
||||
REQUIRE(startServer(server, serverReceivedCloseCode, serverReceivedCloseReason, serverReceivedCloseRemote, mutexWrite));
|
||||
REQUIRE(startServer(server,
|
||||
serverReceivedCloseCode,
|
||||
serverReceivedCloseReason,
|
||||
serverReceivedCloseRemote,
|
||||
mutexWrite));
|
||||
|
||||
std::string session = ix::generateSessionId();
|
||||
WebSocketClient webSocketClient(port);
|
||||
@ -359,7 +356,11 @@ TEST_CASE("Websocket_server_close", "[close]")
|
||||
std::string serverReceivedCloseReason("");
|
||||
std::mutex mutexWrite;
|
||||
|
||||
REQUIRE(startServer(server, serverReceivedCloseCode, serverReceivedCloseReason, serverReceivedCloseRemote, mutexWrite));
|
||||
REQUIRE(startServer(server,
|
||||
serverReceivedCloseCode,
|
||||
serverReceivedCloseReason,
|
||||
serverReceivedCloseRemote,
|
||||
mutexWrite));
|
||||
|
||||
std::string session = ix::generateSessionId();
|
||||
WebSocketClient webSocketClient(port);
|
||||
@ -417,7 +418,11 @@ TEST_CASE("Websocket_server_close_immediatly", "[close]")
|
||||
std::string serverReceivedCloseReason("");
|
||||
std::mutex mutexWrite;
|
||||
|
||||
REQUIRE(startServer(server, serverReceivedCloseCode, serverReceivedCloseReason, serverReceivedCloseRemote, mutexWrite));
|
||||
REQUIRE(startServer(server,
|
||||
serverReceivedCloseCode,
|
||||
serverReceivedCloseReason,
|
||||
serverReceivedCloseRemote,
|
||||
mutexWrite));
|
||||
|
||||
std::string session = ix::generateSessionId();
|
||||
WebSocketClient webSocketClient(port);
|
||||
|
@ -4,12 +4,11 @@
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include <ixwebsocket/IXWebSocket.h>
|
||||
#include <ixwebsocket/IXWebSocketServer.h>
|
||||
#include <ixwebsocket/IXWebSocketMessageQueue.h>
|
||||
|
||||
#include "IXTest.h"
|
||||
#include "catch.hpp"
|
||||
#include <ixwebsocket/IXWebSocket.h>
|
||||
#include <ixwebsocket/IXWebSocketMessageQueue.h>
|
||||
#include <ixwebsocket/IXWebSocketServer.h>
|
||||
#include <thread>
|
||||
|
||||
using namespace ix;
|
||||
@ -18,42 +17,37 @@ namespace
|
||||
{
|
||||
bool startServer(ix::WebSocketServer& server)
|
||||
{
|
||||
server.setOnConnectionCallback(
|
||||
[&server](std::shared_ptr<ix::WebSocket> webSocket,
|
||||
std::shared_ptr<ConnectionState> connectionState)
|
||||
{
|
||||
server.setOnConnectionCallback([&server](std::shared_ptr<ix::WebSocket> webSocket,
|
||||
std::shared_ptr<ConnectionState> connectionState) {
|
||||
webSocket->setOnMessageCallback(
|
||||
[connectionState, &server](const WebSocketMessagePtr& msg)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
Logger() << "New connection";
|
||||
connectionState->computeId();
|
||||
Logger() << "id: " << connectionState->getId();
|
||||
Logger() << "Uri: " << msg->openInfo.uri;
|
||||
Logger() << "Headers:";
|
||||
for (auto&& it : msg->openInfo.headers)
|
||||
[connectionState, &server](const WebSocketMessagePtr& msg) {
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
Logger() << it.first << ": " << it.second;
|
||||
Logger() << "New connection";
|
||||
connectionState->computeId();
|
||||
Logger() << "id: " << connectionState->getId();
|
||||
Logger() << "Uri: " << msg->openInfo.uri;
|
||||
Logger() << "Headers:";
|
||||
for (auto&& it : msg->openInfo.headers)
|
||||
{
|
||||
Logger() << it.first << ": " << it.second;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
Logger() << "Closed connection";
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
Logger() << "Message received: " << msg->str;
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
Logger() << "Closed connection";
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
Logger() << "Message received: " << msg->str;
|
||||
|
||||
for (auto&& client : server.getClients())
|
||||
{
|
||||
client->send(msg->str);
|
||||
for (auto&& client : server.getClients())
|
||||
{
|
||||
client->send(msg->str);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
auto res = server.listen();
|
||||
if (!res.first)
|
||||
@ -73,8 +67,7 @@ namespace
|
||||
{
|
||||
msgQ.bindWebsocket(&ws);
|
||||
|
||||
msgQ.setOnMessageCallback([this](const WebSocketMessagePtr& msg)
|
||||
{
|
||||
msgQ.setOnMessageCallback([this](const WebSocketMessagePtr& msg) {
|
||||
REQUIRE(mainThreadId == std::this_thread::get_id());
|
||||
|
||||
std::stringstream ss;
|
||||
@ -153,7 +146,10 @@ namespace
|
||||
}
|
||||
}
|
||||
|
||||
bool isSucceeded() const { return succeeded; }
|
||||
bool isSucceeded() const
|
||||
{
|
||||
return succeeded;
|
||||
}
|
||||
|
||||
private:
|
||||
WebSocket ws;
|
||||
@ -163,7 +159,7 @@ namespace
|
||||
std::thread::id mainThreadId;
|
||||
bool succeeded = false;
|
||||
};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Websocket_message_queue", "[websocket_message_q]")
|
||||
{
|
||||
|
@ -4,15 +4,13 @@
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXTest.h"
|
||||
#include "catch.hpp"
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <queue>
|
||||
#include <ixwebsocket/IXWebSocket.h>
|
||||
#include <ixwebsocket/IXWebSocketServer.h>
|
||||
|
||||
#include "IXTest.h"
|
||||
|
||||
#include "catch.hpp"
|
||||
#include <queue>
|
||||
#include <sstream>
|
||||
|
||||
using namespace ix;
|
||||
|
||||
@ -20,23 +18,23 @@ namespace
|
||||
{
|
||||
class WebSocketClient
|
||||
{
|
||||
public:
|
||||
WebSocketClient(int port, bool useHeartBeatMethod);
|
||||
public:
|
||||
WebSocketClient(int port, bool useHeartBeatMethod);
|
||||
|
||||
void start();
|
||||
void stop();
|
||||
bool isReady() const;
|
||||
void sendMessage(const std::string& text);
|
||||
void start();
|
||||
void stop();
|
||||
bool isReady() const;
|
||||
void sendMessage(const std::string& text);
|
||||
|
||||
private:
|
||||
ix::WebSocket _webSocket;
|
||||
int _port;
|
||||
bool _useHeartBeatMethod;
|
||||
private:
|
||||
ix::WebSocket _webSocket;
|
||||
int _port;
|
||||
bool _useHeartBeatMethod;
|
||||
};
|
||||
|
||||
WebSocketClient::WebSocketClient(int port, bool useHeartBeatMethod)
|
||||
: _port(port),
|
||||
_useHeartBeatMethod(useHeartBeatMethod)
|
||||
: _port(port)
|
||||
, _useHeartBeatMethod(useHeartBeatMethod)
|
||||
{
|
||||
;
|
||||
}
|
||||
@ -56,9 +54,7 @@ namespace
|
||||
std::string url;
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "ws://127.0.0.1:"
|
||||
<< _port
|
||||
<< "/";
|
||||
ss << "ws://127.0.0.1:" << _port << "/";
|
||||
|
||||
url = ss.str();
|
||||
}
|
||||
@ -79,48 +75,46 @@ namespace
|
||||
std::stringstream ss;
|
||||
log(std::string("Connecting to url: ") + url);
|
||||
|
||||
_webSocket.setOnMessageCallback(
|
||||
[](ix::WebSocketMessageType messageType,
|
||||
const std::string& str,
|
||||
size_t wireSize,
|
||||
const ix::WebSocketErrorInfo& error,
|
||||
const ix::WebSocketOpenInfo& openInfo,
|
||||
const ix::WebSocketCloseInfo& closeInfo)
|
||||
_webSocket.setOnMessageCallback([](ix::WebSocketMessageType messageType,
|
||||
const std::string& str,
|
||||
size_t wireSize,
|
||||
const ix::WebSocketErrorInfo& error,
|
||||
const ix::WebSocketOpenInfo& openInfo,
|
||||
const ix::WebSocketCloseInfo& closeInfo) {
|
||||
std::stringstream ss;
|
||||
if (messageType == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
std::stringstream ss;
|
||||
if (messageType == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
log("client connected");
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
log("client disconnected");
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Error)
|
||||
{
|
||||
ss << "Error ! " << error.reason;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Pong)
|
||||
{
|
||||
ss << "Received pong message " << str;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Ping)
|
||||
{
|
||||
ss << "Received ping message " << str;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
// too many messages to log
|
||||
}
|
||||
else
|
||||
{
|
||||
ss << "Invalid ix::WebSocketMessageType";
|
||||
log(ss.str());
|
||||
}
|
||||
});
|
||||
log("client connected");
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
log("client disconnected");
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Error)
|
||||
{
|
||||
ss << "Error ! " << error.reason;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Pong)
|
||||
{
|
||||
ss << "Received pong message " << str;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Ping)
|
||||
{
|
||||
ss << "Received ping message " << str;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
// too many messages to log
|
||||
}
|
||||
else
|
||||
{
|
||||
ss << "Invalid ix::WebSocketMessageType";
|
||||
log(ss.str());
|
||||
}
|
||||
});
|
||||
|
||||
_webSocket.start();
|
||||
}
|
||||
@ -135,16 +129,15 @@ namespace
|
||||
// A dev/null server
|
||||
server.setOnConnectionCallback(
|
||||
[&server, &receivedPingMessages](std::shared_ptr<ix::WebSocket> webSocket,
|
||||
std::shared_ptr<ConnectionState> connectionState)
|
||||
{
|
||||
std::shared_ptr<ConnectionState> connectionState) {
|
||||
webSocket->setOnMessageCallback(
|
||||
[webSocket, connectionState, &server, &receivedPingMessages](ix::WebSocketMessageType messageType,
|
||||
const std::string& str,
|
||||
size_t wireSize,
|
||||
const ix::WebSocketErrorInfo& error,
|
||||
const ix::WebSocketOpenInfo& openInfo,
|
||||
const ix::WebSocketCloseInfo& closeInfo)
|
||||
{
|
||||
[webSocket, connectionState, &server, &receivedPingMessages](
|
||||
ix::WebSocketMessageType messageType,
|
||||
const std::string& str,
|
||||
size_t wireSize,
|
||||
const ix::WebSocketErrorInfo& error,
|
||||
const ix::WebSocketOpenInfo& openInfo,
|
||||
const ix::WebSocketCloseInfo& closeInfo) {
|
||||
if (messageType == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
Logger() << "New server connection";
|
||||
@ -168,15 +161,13 @@ namespace
|
||||
else if (messageType == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
// to many messages to log
|
||||
for(auto client: server.getClients())
|
||||
for (auto client : server.getClients())
|
||||
{
|
||||
client->sendText("reply");
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
auto res = server.listen();
|
||||
if (!res.first)
|
||||
@ -188,7 +179,7 @@ namespace
|
||||
server.start();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Websocket_ping_no_data_sent_setPingInterval", "[setPingInterval]")
|
||||
{
|
||||
@ -282,7 +273,8 @@ TEST_CASE("Websocket_ping_data_sent_setPingInterval", "[setPingInterval]")
|
||||
|
||||
TEST_CASE("Websocket_ping_data_sent_setPingInterval_half_full", "[setPingInterval]")
|
||||
{
|
||||
SECTION("Make sure that ping messages are sent, even if other messages are sent continuously during a given time")
|
||||
SECTION("Make sure that ping messages are sent, even if other messages are sent continuously "
|
||||
"during a given time")
|
||||
{
|
||||
ix::setupWebSocketTrafficTrackerCallback();
|
||||
|
||||
@ -309,7 +301,7 @@ TEST_CASE("Websocket_ping_data_sent_setPingInterval_half_full", "[setPingInterva
|
||||
// send continuously for 1100ms
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
|
||||
while(std::chrono::steady_clock::now() - now <= std::chrono::milliseconds(900))
|
||||
while (std::chrono::steady_clock::now() - now <= std::chrono::milliseconds(900))
|
||||
{
|
||||
webSocketClient.sendMessage("message");
|
||||
ix::msleep(1);
|
||||
@ -335,7 +327,8 @@ TEST_CASE("Websocket_ping_data_sent_setPingInterval_half_full", "[setPingInterva
|
||||
|
||||
TEST_CASE("Websocket_ping_data_sent_setPingInterval_full", "[setPingInterval]")
|
||||
{
|
||||
SECTION("Make sure that ping messages are sent, even if other messages are sent continuously for longer than ping interval")
|
||||
SECTION("Make sure that ping messages are sent, even if other messages are sent continuously "
|
||||
"for longer than ping interval")
|
||||
{
|
||||
ix::setupWebSocketTrafficTrackerCallback();
|
||||
|
||||
@ -362,7 +355,7 @@ TEST_CASE("Websocket_ping_data_sent_setPingInterval_full", "[setPingInterval]")
|
||||
// send continuously for 1100ms
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
|
||||
while(std::chrono::steady_clock::now() - now <= std::chrono::milliseconds(1100))
|
||||
while (std::chrono::steady_clock::now() - now <= std::chrono::milliseconds(1100))
|
||||
{
|
||||
webSocketClient.sendMessage("message");
|
||||
ix::msleep(1);
|
||||
|
@ -4,15 +4,13 @@
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXTest.h"
|
||||
#include "catch.hpp"
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <queue>
|
||||
#include <ixwebsocket/IXWebSocket.h>
|
||||
#include <ixwebsocket/IXWebSocketServer.h>
|
||||
|
||||
#include "IXTest.h"
|
||||
|
||||
#include "catch.hpp"
|
||||
#include <queue>
|
||||
#include <sstream>
|
||||
|
||||
using namespace ix;
|
||||
|
||||
@ -20,32 +18,32 @@ namespace
|
||||
{
|
||||
class WebSocketClient
|
||||
{
|
||||
public:
|
||||
WebSocketClient(int port, int pingInterval, int pingTimeout);
|
||||
public:
|
||||
WebSocketClient(int port, int pingInterval, int pingTimeout);
|
||||
|
||||
void start();
|
||||
void stop();
|
||||
bool isReady() const;
|
||||
bool isClosed() const;
|
||||
void sendMessage(const std::string& text);
|
||||
int getReceivedPongMessages();
|
||||
bool closedDueToPingTimeout();
|
||||
void start();
|
||||
void stop();
|
||||
bool isReady() const;
|
||||
bool isClosed() const;
|
||||
void sendMessage(const std::string& text);
|
||||
int getReceivedPongMessages();
|
||||
bool closedDueToPingTimeout();
|
||||
|
||||
private:
|
||||
ix::WebSocket _webSocket;
|
||||
int _port;
|
||||
int _pingInterval;
|
||||
int _pingTimeout;
|
||||
std::atomic<int> _receivedPongMessages;
|
||||
std::atomic<bool> _closedDueToPingTimeout;
|
||||
private:
|
||||
ix::WebSocket _webSocket;
|
||||
int _port;
|
||||
int _pingInterval;
|
||||
int _pingTimeout;
|
||||
std::atomic<int> _receivedPongMessages;
|
||||
std::atomic<bool> _closedDueToPingTimeout;
|
||||
};
|
||||
|
||||
WebSocketClient::WebSocketClient(int port, int pingInterval, int pingTimeout)
|
||||
: _port(port),
|
||||
_receivedPongMessages(0),
|
||||
_closedDueToPingTimeout(false),
|
||||
_pingInterval(pingInterval),
|
||||
_pingTimeout(pingTimeout)
|
||||
: _port(port)
|
||||
, _receivedPongMessages(0)
|
||||
, _closedDueToPingTimeout(false)
|
||||
, _pingInterval(pingInterval)
|
||||
, _pingTimeout(pingTimeout)
|
||||
{
|
||||
;
|
||||
}
|
||||
@ -70,9 +68,7 @@ namespace
|
||||
std::string url;
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "ws://127.0.0.1:"
|
||||
<< _port
|
||||
<< "/";
|
||||
ss << "ws://127.0.0.1:" << _port << "/";
|
||||
|
||||
url = ss.str();
|
||||
}
|
||||
@ -88,58 +84,54 @@ namespace
|
||||
std::stringstream ss;
|
||||
log(std::string("Connecting to url: ") + url);
|
||||
|
||||
_webSocket.setOnMessageCallback(
|
||||
[this](ix::WebSocketMessageType messageType,
|
||||
const std::string& str,
|
||||
size_t wireSize,
|
||||
const ix::WebSocketErrorInfo& error,
|
||||
const ix::WebSocketOpenInfo& openInfo,
|
||||
const ix::WebSocketCloseInfo& closeInfo)
|
||||
_webSocket.setOnMessageCallback([this](ix::WebSocketMessageType messageType,
|
||||
const std::string& str,
|
||||
size_t wireSize,
|
||||
const ix::WebSocketErrorInfo& error,
|
||||
const ix::WebSocketOpenInfo& openInfo,
|
||||
const ix::WebSocketCloseInfo& closeInfo) {
|
||||
std::stringstream ss;
|
||||
if (messageType == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
std::stringstream ss;
|
||||
if (messageType == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
log("client connected");
|
||||
log("client connected");
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
log("client disconnected");
|
||||
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Close)
|
||||
if (msg->closeInfo.code == 1011)
|
||||
{
|
||||
log("client disconnected");
|
||||
_closedDueToPingTimeout = true;
|
||||
}
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Error)
|
||||
{
|
||||
ss << "Error ! " << error.reason;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Pong)
|
||||
{
|
||||
_receivedPongMessages++;
|
||||
|
||||
if (msg->closeInfo.code == 1011)
|
||||
{
|
||||
_closedDueToPingTimeout = true;
|
||||
}
|
||||
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Error)
|
||||
{
|
||||
ss << "Error ! " << error.reason;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Pong)
|
||||
{
|
||||
_receivedPongMessages++;
|
||||
|
||||
ss << "Received pong message " << str;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Ping)
|
||||
{
|
||||
ss << "Received ping message " << str;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
ss << "Received message " << str;
|
||||
log(ss.str());
|
||||
}
|
||||
else
|
||||
{
|
||||
ss << "Invalid ix::WebSocketMessageType";
|
||||
log(ss.str());
|
||||
}
|
||||
});
|
||||
ss << "Received pong message " << str;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Ping)
|
||||
{
|
||||
ss << "Received ping message " << str;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (messageType == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
ss << "Received message " << str;
|
||||
log(ss.str());
|
||||
}
|
||||
else
|
||||
{
|
||||
ss << "Invalid ix::WebSocketMessageType";
|
||||
log(ss.str());
|
||||
}
|
||||
});
|
||||
|
||||
_webSocket.start();
|
||||
}
|
||||
@ -159,21 +151,22 @@ namespace
|
||||
return _closedDueToPingTimeout;
|
||||
}
|
||||
|
||||
bool startServer(ix::WebSocketServer& server, std::atomic<int>& receivedPingMessages, bool enablePong)
|
||||
bool startServer(ix::WebSocketServer& server,
|
||||
std::atomic<int>& receivedPingMessages,
|
||||
bool enablePong)
|
||||
{
|
||||
// A dev/null server
|
||||
server.setOnConnectionCallback(
|
||||
[&server, &receivedPingMessages](std::shared_ptr<ix::WebSocket> webSocket,
|
||||
std::shared_ptr<ConnectionState> connectionState)
|
||||
{
|
||||
std::shared_ptr<ConnectionState> connectionState) {
|
||||
webSocket->setOnMessageCallback(
|
||||
[webSocket, connectionState, &server, &receivedPingMessages](ix::WebSocketMessageType messageType,
|
||||
const std::string& str,
|
||||
size_t wireSize,
|
||||
const ix::WebSocketErrorInfo& error,
|
||||
const ix::WebSocketOpenInfo& openInfo,
|
||||
const ix::WebSocketCloseInfo& closeInfo)
|
||||
{
|
||||
[webSocket, connectionState, &server, &receivedPingMessages](
|
||||
ix::WebSocketMessageType messageType,
|
||||
const std::string& str,
|
||||
size_t wireSize,
|
||||
const ix::WebSocketErrorInfo& error,
|
||||
const ix::WebSocketOpenInfo& openInfo,
|
||||
const ix::WebSocketCloseInfo& closeInfo) {
|
||||
if (messageType == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
Logger() << "New server connection";
|
||||
@ -194,10 +187,8 @@ namespace
|
||||
log("Server received a ping");
|
||||
receivedPingMessages++;
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
if (!enablePong)
|
||||
{
|
||||
@ -215,7 +206,7 @@ namespace
|
||||
server.start();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Websocket_ping_timeout_not_checked", "[setPingTimeout]")
|
||||
{
|
||||
@ -336,7 +327,7 @@ TEST_CASE("Websocket_no_ping_but_timeout", "[setPingTimeout]")
|
||||
REQUIRE(startServer(server, serverReceivedPingMessages, enablePong));
|
||||
|
||||
std::string session = ix::generateSessionId();
|
||||
int pingIntervalSecs = -1; // no ping set
|
||||
int pingIntervalSecs = -1; // no ping set
|
||||
int pingTimeoutSecs = 3;
|
||||
WebSocketClient webSocketClient(port, pingIntervalSecs, pingTimeoutSecs);
|
||||
webSocketClient.start();
|
||||
|
@ -4,15 +4,13 @@
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXTest.h"
|
||||
#include "catch.hpp"
|
||||
#include <iostream>
|
||||
#include <ixwebsocket/IXSocket.h>
|
||||
#include <ixwebsocket/IXSocketFactory.h>
|
||||
#include <ixwebsocket/IXWebSocket.h>
|
||||
#include <ixwebsocket/IXWebSocketServer.h>
|
||||
#include <ixwebsocket/IXSocketFactory.h>
|
||||
|
||||
#include "IXTest.h"
|
||||
|
||||
#include "catch.hpp"
|
||||
|
||||
using namespace ix;
|
||||
|
||||
@ -28,55 +26,48 @@ namespace ix
|
||||
}
|
||||
};
|
||||
|
||||
bool startServer(ix::WebSocketServer& server,
|
||||
std::string& connectionId)
|
||||
bool startServer(ix::WebSocketServer& server, std::string& connectionId)
|
||||
{
|
||||
auto factory = []() -> std::shared_ptr<ConnectionState>
|
||||
{
|
||||
auto factory = []() -> std::shared_ptr<ConnectionState> {
|
||||
return std::make_shared<ConnectionStateCustom>();
|
||||
};
|
||||
server.setConnectionStateFactory(factory);
|
||||
|
||||
server.setOnConnectionCallback(
|
||||
[&server, &connectionId](std::shared_ptr<ix::WebSocket> webSocket,
|
||||
std::shared_ptr<ConnectionState> connectionState)
|
||||
{
|
||||
webSocket->setOnMessageCallback(
|
||||
[webSocket, connectionState,
|
||||
&connectionId, &server](const ix::WebSocketMessagePtr& msg)
|
||||
server.setOnConnectionCallback([&server, &connectionId](
|
||||
std::shared_ptr<ix::WebSocket> webSocket,
|
||||
std::shared_ptr<ConnectionState> connectionState) {
|
||||
webSocket->setOnMessageCallback([webSocket, connectionState, &connectionId, &server](
|
||||
const ix::WebSocketMessagePtr& msg) {
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
Logger() << "New connection";
|
||||
connectionState->computeId();
|
||||
Logger() << "id: " << connectionState->getId();
|
||||
Logger() << "Uri: " << msg->openInfo.uri;
|
||||
Logger() << "Headers:";
|
||||
for (auto it : msg->openInfo.headers)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
Logger() << "New connection";
|
||||
connectionState->computeId();
|
||||
Logger() << "id: " << connectionState->getId();
|
||||
Logger() << "Uri: " << msg->openInfo.uri;
|
||||
Logger() << "Headers:";
|
||||
for (auto it : msg->openInfo.headers)
|
||||
{
|
||||
Logger() << it.first << ": " << it.second;
|
||||
}
|
||||
Logger() << it.first << ": " << it.second;
|
||||
}
|
||||
|
||||
connectionId = connectionState->getId();
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
connectionId = connectionState->getId();
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
Logger() << "Closed connection";
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
for (auto&& client : server.getClients())
|
||||
{
|
||||
if (client != webSocket)
|
||||
{
|
||||
Logger() << "Closed connection";
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
for (auto&& client : server.getClients())
|
||||
{
|
||||
if (client != webSocket)
|
||||
{
|
||||
client->send(msg->str);
|
||||
}
|
||||
}
|
||||
client->send(msg->str);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
auto res = server.listen();
|
||||
if (!res.first)
|
||||
@ -88,7 +79,7 @@ namespace ix
|
||||
server.start();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} // namespace ix
|
||||
|
||||
TEST_CASE("Websocket_server", "[websocket_server]")
|
||||
{
|
||||
@ -103,10 +94,7 @@ TEST_CASE("Websocket_server", "[websocket_server]")
|
||||
bool tls = false;
|
||||
std::shared_ptr<Socket> socket = createSocket(tls, errMsg);
|
||||
std::string host("127.0.0.1");
|
||||
auto isCancellationRequested = []() -> bool
|
||||
{
|
||||
return false;
|
||||
};
|
||||
auto isCancellationRequested = []() -> bool { return false; };
|
||||
bool success = socket->connect(host, port, errMsg, isCancellationRequested);
|
||||
REQUIRE(success);
|
||||
|
||||
@ -139,10 +127,7 @@ TEST_CASE("Websocket_server", "[websocket_server]")
|
||||
bool tls = false;
|
||||
std::shared_ptr<Socket> socket = createSocket(tls, errMsg);
|
||||
std::string host("127.0.0.1");
|
||||
auto isCancellationRequested = []() -> bool
|
||||
{
|
||||
return false;
|
||||
};
|
||||
auto isCancellationRequested = []() -> bool { return false; };
|
||||
bool success = socket->connect(host, port, errMsg, isCancellationRequested);
|
||||
REQUIRE(success);
|
||||
|
||||
@ -178,10 +163,7 @@ TEST_CASE("Websocket_server", "[websocket_server]")
|
||||
bool tls = false;
|
||||
std::shared_ptr<Socket> socket = createSocket(tls, errMsg);
|
||||
std::string host("127.0.0.1");
|
||||
auto isCancellationRequested = []() -> bool
|
||||
{
|
||||
return false;
|
||||
};
|
||||
auto isCancellationRequested = []() -> bool { return false; };
|
||||
bool success = socket->connect(host, port, errMsg, isCancellationRequested);
|
||||
REQUIRE(success);
|
||||
|
||||
|
@ -4,13 +4,12 @@
|
||||
* Copyright (c) 2017 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <set>
|
||||
#include <ixwebsocket/IXWebSocket.h>
|
||||
#include "IXTest.h"
|
||||
|
||||
#include "catch.hpp"
|
||||
#include <iostream>
|
||||
#include <ixwebsocket/IXWebSocket.h>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
|
||||
using namespace ix;
|
||||
|
||||
@ -19,19 +18,19 @@ namespace
|
||||
const std::string WEBSOCKET_DOT_ORG_URL("wss://echo.websocket.org");
|
||||
const std::string GOOGLE_URL("wss://google.com");
|
||||
const std::string UNKNOWN_URL("wss://asdcasdcaasdcasdcasdcasdcasdcasdcasassdd.com");
|
||||
}
|
||||
} // namespace
|
||||
|
||||
namespace
|
||||
{
|
||||
class IXWebSocketTestConnectionDisconnection
|
||||
{
|
||||
public:
|
||||
IXWebSocketTestConnectionDisconnection();
|
||||
void start(const std::string& url);
|
||||
void stop();
|
||||
public:
|
||||
IXWebSocketTestConnectionDisconnection();
|
||||
void start(const std::string& url);
|
||||
void stop();
|
||||
|
||||
private:
|
||||
ix::WebSocket _webSocket;
|
||||
private:
|
||||
ix::WebSocket _webSocket;
|
||||
};
|
||||
|
||||
IXWebSocketTestConnectionDisconnection::IXWebSocketTestConnectionDisconnection()
|
||||
@ -51,45 +50,43 @@ namespace
|
||||
std::stringstream ss;
|
||||
log(std::string("Connecting to url: ") + url);
|
||||
|
||||
_webSocket.setOnMessageCallback(
|
||||
[](const ix::WebSocketMessagePtr& msg)
|
||||
_webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg) {
|
||||
std::stringstream ss;
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
std::stringstream ss;
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
log("TestConnectionDisconnection: connected !");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
log("TestConnectionDisconnection: disconnected !");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Error)
|
||||
{
|
||||
ss << "TestConnectionDisconnection: Error! ";
|
||||
ss << msg->errorInfo.reason;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
log("TestConnectionDisconnection: received message.!");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Ping)
|
||||
{
|
||||
log("TestConnectionDisconnection: received ping message.!");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Pong)
|
||||
{
|
||||
log("TestConnectionDisconnection: received pong message.!");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Fragment)
|
||||
{
|
||||
log("TestConnectionDisconnection: received fragment.!");
|
||||
}
|
||||
else
|
||||
{
|
||||
log("Invalid ix::WebSocketMessageType");
|
||||
}
|
||||
});
|
||||
log("TestConnectionDisconnection: connected !");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
log("TestConnectionDisconnection: disconnected !");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Error)
|
||||
{
|
||||
ss << "TestConnectionDisconnection: Error! ";
|
||||
ss << msg->errorInfo.reason;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
log("TestConnectionDisconnection: received message.!");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Ping)
|
||||
{
|
||||
log("TestConnectionDisconnection: received ping message.!");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Pong)
|
||||
{
|
||||
log("TestConnectionDisconnection: received pong message.!");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Fragment)
|
||||
{
|
||||
log("TestConnectionDisconnection: received fragment.!");
|
||||
}
|
||||
else
|
||||
{
|
||||
log("Invalid ix::WebSocketMessageType");
|
||||
}
|
||||
});
|
||||
|
||||
_webSocket.enableAutomaticReconnection();
|
||||
REQUIRE(_webSocket.isAutomaticReconnectionEnabled() == true);
|
||||
@ -100,11 +97,12 @@ namespace
|
||||
// Start the connection
|
||||
_webSocket.start();
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
//
|
||||
// We try to connect to different servers, and make sure there are no crashes.
|
||||
// FIXME: We could do more checks (make sure that we were not able to connect to unknown servers, etc...)
|
||||
// FIXME: We could do more checks (make sure that we were not able to connect to unknown servers,
|
||||
// etc...)
|
||||
//
|
||||
TEST_CASE("websocket_connections", "[websocket]")
|
||||
{
|
||||
@ -121,7 +119,8 @@ TEST_CASE("websocket_connections", "[websocket]")
|
||||
test.stop();
|
||||
}
|
||||
|
||||
SECTION("Try to connect and disconnect with different timing, not enough time to succesfully connect")
|
||||
SECTION("Try to connect and disconnect with different timing, not enough time to succesfully "
|
||||
"connect")
|
||||
{
|
||||
IXWebSocketTestConnectionDisconnection test;
|
||||
log(std::string("50 Runs"));
|
||||
@ -141,7 +140,8 @@ TEST_CASE("websocket_connections", "[websocket]")
|
||||
|
||||
// This test breaks on travis CI - Ubuntu Xenial + gcc + tsan
|
||||
// We should fix this.
|
||||
SECTION("Try to connect and disconnect with different timing, from not enough time to successfull connect")
|
||||
SECTION("Try to connect and disconnect with different timing, from not enough time to "
|
||||
"successfull connect")
|
||||
{
|
||||
IXWebSocketTestConnectionDisconnection test;
|
||||
log(std::string("20 Runs"));
|
||||
@ -152,7 +152,7 @@ TEST_CASE("websocket_connections", "[websocket]")
|
||||
test.start(WEBSOCKET_DOT_ORG_URL);
|
||||
|
||||
log(std::string("Sleeping"));
|
||||
ix::msleep(i*50);
|
||||
ix::msleep(i * 50);
|
||||
|
||||
log(std::string("Stopping"));
|
||||
test.stop();
|
||||
|
@ -6,20 +6,15 @@
|
||||
|
||||
#define CATCH_CONFIG_RUNNER
|
||||
#include "catch.hpp"
|
||||
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
#include <ixwebsocket/IXNetSystem.h>
|
||||
#include <ixcore/utils/IXCoreLogger.h>
|
||||
#include <ixwebsocket/IXNetSystem.h>
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
ix::initNetSystem();
|
||||
|
||||
ix::IXCoreLogger::LogFunc logFunc = [](const char* msg)
|
||||
{
|
||||
spdlog::info(msg);
|
||||
};
|
||||
ix::IXCoreLogger::LogFunc logFunc = [](const char* msg) { spdlog::info(msg); };
|
||||
ix::IXCoreLogger::setLogFunction(logFunc);
|
||||
|
||||
int result = Catch::Session().run(argc, argv);
|
||||
|
Reference in New Issue
Block a user