Last active
May 17, 2019 10:41
-
-
Save naezith/a1d9bd47cda86ca448bafc781a823b24 to your computer and use it in GitHub Desktop.
Socket Stress using SFML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <SFML/Network.hpp> | |
#include <iostream> | |
#include <chrono> | |
#include <future> | |
#include <cstring> | |
int main() { | |
// Parameters | |
const auto ip = "111.111.111.111"; | |
const auto port = 7777; | |
const auto data = "POST / HTTP/1.1\r\nHost: 111.111.111.111:7777\r\nAuthorization:\r\nUser-Agent: *\r\nContent-Type: text/plain\r\nContent-Length: 8\r\n\r\n{\"\"}"; | |
const auto sync = false; | |
std::vector<sf::TcpSocket> sockets(25); | |
// Threads | |
std::vector<std::future<void>> connect_futures(sockets.size()); | |
std::vector<std::future<void>> send_futures (sockets.size()); | |
// Counters | |
auto connected = 0; | |
auto sent = 0; | |
// Functions | |
auto connect_func = [&](const auto i) { if(sockets[i].connect(ip, port, sf::seconds(5)) == sf::Socket::Done) ++connected; }; | |
auto send_func = [&](const auto i) { if(sockets[i].send(data, strlen(data)) == sf::Socket::Done) ++sent; }; | |
auto run = [&](const auto& func, auto& futures, const auto& success_count, const auto& action_msg) { | |
auto start = std::chrono::steady_clock::now(); | |
if(sync) for(size_t i = 0; i < sockets.size(); ++i) func(i); | |
else { | |
for(size_t i = 0; i < sockets.size(); ++i) futures[i] = std::async(std::launch::async, func, i); | |
for(size_t i = 0; i < sockets.size(); ++i) futures[i].get(); | |
} | |
auto end = std::chrono::steady_clock::now(); | |
// Log | |
std::cout << action_msg << " to " << success_count << " sockets in " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms" << std::endl; | |
}; | |
// Start | |
std::cout << "Message: \n\n" << data << "\n" << std::endl; | |
std::cout << "Message length: " << strlen(data) << "\n\n" << std::endl; | |
std::cout << "Will try to connect to " << sockets.size() << " sockets " << (sync ? "synchronously, it will take a while..." : "at the same time, asynchronously...") << std::endl; | |
run(connect_func, connect_futures, connected, "Connected"); | |
run(send_func, send_futures, sent, "Sent"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment