Skip to content

Commit

Permalink
update example
Browse files Browse the repository at this point in the history
  • Loading branch information
IronsDu committed Jun 1, 2019
1 parent f347d00 commit e11fa11
Show file tree
Hide file tree
Showing 5 changed files with 156 additions and 126 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ Examples

Users
----------------------------
* [ARK - distributed plugin framework](https://github.com/ArkNX/ARK)
* [Redis proxy](https://github.com/IronsDu/DBProxy)
* [Distributed game server framework](https://github.com/IronsDu/DServerFramework)
* [gayrpc](https://github.com/IronsDu/gayrpc)
* [Joynet - Lua network library](https://github.com/IronsDu/Joynet)
* [HTTP-RPC](https://github.com/IronsDu/http-rpc)
* [grpc-gateway](https://github.com/IronsDu/grpc-gateway)
85 changes: 48 additions & 37 deletions examples/BenchWebsocket.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include <brynet/net/http/HttpFormat.h>
#include <brynet/net/http/WebSocketFormat.h>
#include <brynet/utils/packet.h>
#include <brynet/net/Wrapper.h>

using namespace brynet;
using namespace brynet::net;
Expand Down Expand Up @@ -51,49 +52,59 @@ int main(int argc, char **argv)
size_t workers = argc > 4 ? std::atoi(argv[4]) : std::thread::hardware_concurrency();

std::cout << "host: " << host << ':' << port << " | connections: " << connections << " | workers: " << workers << std::endl;

auto service = TcpService::Create();
service->startWorkerThread(workers);

for (int i = 0; i < connections; i++)
{
sock fd = brynet::net::base::Connect(false, host, port);
auto socket = TcpSocket::Create(fd, false);
brynet::net::base::SocketNodelay(fd);

auto enterCallback = [host](const TcpConnection::Ptr& session) {
HttpService::setup(session, [host](const HttpSession::Ptr& httpSession) {
HttpRequest request;
request.setMethod(HttpRequest::HTTP_METHOD::HTTP_METHOD_GET);
request.setUrl("/ws");
request.addHeadValue("Host", host);
request.addHeadValue("Upgrade", "websocket");
request.addHeadValue("Connection", "Upgrade");
request.addHeadValue("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
request.addHeadValue("Sec-WebSocket-Version", "13");
auto enterCallback = [host](const HttpSession::Ptr& httpSession) {
HttpRequest request;
request.setMethod(HttpRequest::HTTP_METHOD::HTTP_METHOD_GET);
request.setUrl("/ws");
request.addHeadValue("Host", host);
request.addHeadValue("Upgrade", "websocket");
request.addHeadValue("Connection", "Upgrade");
request.addHeadValue("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
request.addHeadValue("Sec-WebSocket-Version", "13");

std::string requestStr = request.getResult();
httpSession->send(requestStr.c_str(), requestStr.size());
std::string requestStr = request.getResult();
httpSession->send(requestStr.c_str(), requestStr.size());

httpSession->setWSConnected([](const HttpSession::Ptr& session, const HTTPParser&) {
for (int i = 0; i < 200; i++)
{
sendPacket(session, "hello, world!", 13);
}
});

httpSession->setWSCallback([](const HttpSession::Ptr& session,
WebSocketFormat::WebSocketFrameType, const std::string& payload) {
std::cout << payload << std::endl;
httpSession->setWSConnected([](const HttpSession::Ptr& session, const HTTPParser&) {
for (int i = 0; i < 200; i++)
{
sendPacket(session, "hello, world!", 13);
count += 1;
});
}
});

httpSession->setWSCallback([](const HttpSession::Ptr& session,
WebSocketFormat::WebSocketFrameType, const std::string& payload) {
std::cout << payload << std::endl;
sendPacket(session, "hello, world!", 13);
count += 1;
});
};
};

auto service = TcpService::Create();
service->startWorkerThread(workers);

service->addTcpConnection(std::move(socket),
brynet::net::TcpService::AddSocketOption::AddEnterCallback(enterCallback),
brynet::net::TcpService::AddSocketOption::WithMaxRecvBufferSize(1024*1024));
auto connector = AsyncConnector::Create();
connector->startWorkerThread();

wrapper::HttpConnectionBuilder connectionBuilder;
connectionBuilder.configureService(service)
.configureConnector(connector)
.configureConnectionOptions({
brynet::net::TcpService::AddSocketOption::WithMaxRecvBufferSize(1024 * 1024)
});

for (int i = 0; i < connections; i++)
{
connectionBuilder.configureConnectOptions({
AsyncConnector::ConnectOptions::WithAddr(host, port),
AsyncConnector::ConnectOptions::WithTimeout(std::chrono::seconds(10)),
AsyncConnector::ConnectOptions::AddProcessTcpSocketCallback([](TcpSocket& socket) {
socket.setNodelay();
})
})
.configureEnterCallback(enterCallback)
.asyncConnect();
}

brynet::net::EventLoop mainLoop;
Expand Down
60 changes: 32 additions & 28 deletions examples/PingPongClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include <brynet/net/SocketLibFunction.h>
#include <brynet/net/TCPService.h>
#include <brynet/net/Connector.h>
#include <brynet/net/Wrapper.h>

using namespace brynet;
using namespace brynet::net;
Expand All @@ -18,42 +19,45 @@ int main(int argc, char **argv)

std::string tmp(atoi(argv[5]), 'a');

auto server = TcpService::Create();
server->startWorkerThread(atoi(argv[3]));
auto service = TcpService::Create();
service->startWorkerThread(atoi(argv[3]));

auto connector = AsyncConnector::Create();
connector->startWorkerThread();

auto enterCallback = [tmp](const TcpConnection::Ptr& session) {
session->setDataCallback([session](const char* buffer, size_t len) {
session->send(buffer, len);
return len;
});
session->send(tmp.c_str(), tmp.size());
};

auto failedCallback = []() {
std::cout << "connect failed" << std::endl;
};

wrapper::ConnectionBuilder connectionBuilder;
connectionBuilder.configureService(service)
.configureConnector(connector)
.configureConnectionOptions({
brynet::net::TcpService::AddSocketOption::AddEnterCallback(enterCallback),
brynet::net::TcpService::AddSocketOption::WithMaxRecvBufferSize(1024 * 1024)
});

for (auto i = 0; i < atoi(argv[4]); i++)
{
try
{
auto enterCallback = [server, tmp](TcpSocket::Ptr socket) {
std::cout << "connect success" << std::endl;
socket->setNodelay();

auto enterCallback = [tmp](const TcpConnection::Ptr& session) {
session->setDataCallback([session](const char* buffer, size_t len) {
session->send(buffer, len);
return len;
});
session->send(tmp.c_str(), tmp.size());
};

server->addTcpConnection(std::move(socket),
brynet::net::TcpService::AddSocketOption::AddEnterCallback(enterCallback),
brynet::net::TcpService::AddSocketOption::WithMaxRecvBufferSize(1024 * 1024));
};

auto failedCallback = []() {
std::cout << "connect failed" << std::endl;
};

connector->asyncConnect({
AsyncConnector::ConnectOptions::WithAddr(argv[1], atoi(argv[2])),
AsyncConnector::ConnectOptions::WithTimeout(std::chrono::seconds(10)),
AsyncConnector::ConnectOptions::WithCompletedCallback(enterCallback),
AsyncConnector::ConnectOptions::WithFailedCallback(failedCallback)});
connectionBuilder.configureConnectOptions({
AsyncConnector::ConnectOptions::WithAddr(argv[1], atoi(argv[2])),
AsyncConnector::ConnectOptions::WithTimeout(std::chrono::seconds(10)),
AsyncConnector::ConnectOptions::WithFailedCallback(failedCallback),
AsyncConnector::ConnectOptions::AddProcessTcpSocketCallback([](TcpSocket& socket) {
socket.setNodelay();
})
})
.asyncConnect();
}
catch (std::runtime_error& e)
{
Expand Down
46 changes: 25 additions & 21 deletions examples/PingPongServer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@
#include <mutex>
#include <atomic>

#include <brynet/net/SocketLibFunction.h>
#include <brynet/net/EventLoop.h>
#include <brynet/net/TCPService.h>
#include <brynet/net/ListenThread.h>
#include <brynet/net/Socket.h>
#include <brynet/net/Wrapper.h>

using namespace brynet;
using namespace brynet::net;
Expand All @@ -23,33 +21,39 @@ int main(int argc, char **argv)
exit(-1);
}

auto server = TcpService::Create();
auto listenThread = ListenThread::Create(false, "0.0.0.0", atoi(argv[1]), [=](TcpSocket::Ptr socket) {
socket->setNodelay();
auto service = TcpService::Create();
service->startWorkerThread(atoi(argv[2]));

auto enterCallback = [](const TcpConnection::Ptr& session) {
total_client_num++;
auto enterCallback = [](const TcpConnection::Ptr& session) {
total_client_num++;

session->setDataCallback([session](const char* buffer, size_t len) {
session->setDataCallback([session](const char* buffer, size_t len) {
session->send(buffer, len);
TotalRecvSize += len;
total_packet_num++;
return len;
});
});

session->setDisConnectCallback([](const TcpConnection::Ptr& session) {
session->setDisConnectCallback([](const TcpConnection::Ptr& session) {
total_client_num--;
});
};
});
};

server->addTcpConnection(std::move(socket),
brynet::net::TcpService::AddSocketOption::AddEnterCallback(enterCallback),
brynet::net::TcpService::AddSocketOption::WithMaxRecvBufferSize(1024 * 1024));
});

listenThread->startListen();

server->startWorkerThread(atoi(argv[2]));
wrapper::ListenerBuilder listener;
listener.configureService(service)
.configureSocketOptions({
[](TcpSocket& socket) {
socket.setNodelay();
}
})
.configureConnectionOptions({
brynet::net::TcpService::AddSocketOption::WithMaxRecvBufferSize(1024 * 1024),
brynet::net::TcpService::AddSocketOption::AddEnterCallback(enterCallback)
})
.configureListen([=](wrapper::BuildListenConfig config) {
config.setAddr(false, "0.0.0.0", atoi(argv[1]));
})
.asyncRun();

EventLoop mainLoop;
while (true)
Expand Down
87 changes: 49 additions & 38 deletions examples/TestPromiseReceive.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <brynet/net/PromiseReceive.h>
#include <brynet/net/http/HttpFormat.h>
#include <brynet/net/ListenThread.h>
#include <brynet/net/Wrapper.h>

using namespace brynet;
using namespace brynet::net;
Expand All @@ -21,53 +22,63 @@ int main(int argc, char **argv)
exit(-1);
}

auto server = TcpService::Create();
auto listenThread = ListenThread::Create(false, "0.0.0.0", atoi(argv[1]), [=](TcpSocket::Ptr socket) {
socket->setNodelay();
auto enterCallback = [](const TcpConnection::Ptr& session) {
auto promiseReceive = setupPromiseReceive(session);
auto contentLength = std::make_shared<size_t>();
auto service = TcpService::Create();
service->startWorkerThread(atoi(argv[2]));

promiseReceive->receiveUntil("\r\n", [](const char* buffer, size_t len) {
auto enterCallback = [](const TcpConnection::Ptr& session) {
auto promiseReceive = setupPromiseReceive(session);
auto contentLength = std::make_shared<size_t>();

promiseReceive
->receiveUntil("\r\n", [](const char* buffer, size_t len) {
auto headline = std::string(buffer, len);
std::cout << headline << std::endl;
return false;
})->receiveUntil("\r\n", [promiseReceive, contentLength](const char* buffer, size_t len) {
auto headerValue = std::string(buffer, len);
std::cout << headerValue << std::endl;
if (len > 2)
})
->receiveUntil("\r\n", [promiseReceive, contentLength](const char* buffer, size_t len) {
auto headerValue = std::string(buffer, len);
std::cout << headerValue << std::endl;
if (len > 2)
{
const static std::string ContentLenghtFlag = "Content-Length: ";
auto pos = headerValue.find(ContentLenghtFlag);
if (pos != std::string::npos)
{
const static std::string ContentLenghtFlag = "Content-Length: ";
auto pos = headerValue.find(ContentLenghtFlag);
if (pos != std::string::npos)
{
auto lenStr = headerValue.substr(pos + ContentLenghtFlag.size(), headerValue.size());
*contentLength = std::stoi(lenStr);
}
return true;
auto lenStr = headerValue.substr(pos + ContentLenghtFlag.size(), headerValue.size());
*contentLength = std::stoi(lenStr);
}
return false;
})->receive(contentLength, [session](const char* buffer, size_t len) {
HttpResponse response;
response.setStatus(HttpResponse::HTTP_RESPONSE_STATUS::OK);
response.setContentType("text/html; charset=utf-8");
response.setBody("<html>hello world </html>");

auto result = response.getResult();
session->send(result.c_str(), result.size());
session->postShutdown();
return true;
}
return false;
})->receive(contentLength, [session](const char* buffer, size_t len) {
HttpResponse response;
response.setStatus(HttpResponse::HTTP_RESPONSE_STATUS::OK);
response.setContentType("text/html; charset=utf-8");
response.setBody("<html>hello world </html>");

return false;
});
};
server->addTcpConnection(std::move(socket),
brynet::net::TcpService::AddSocketOption::AddEnterCallback(enterCallback),
brynet::net::TcpService::AddSocketOption::WithMaxRecvBufferSize(10));
});
auto result = response.getResult();
session->send(result.c_str(), result.size());
session->postShutdown();

listenThread->startListen();
return false;
});
};

server->startWorkerThread(atoi(argv[2]));
wrapper::ListenerBuilder listener;
listener.configureService(service)
.configureSocketOptions({
[](TcpSocket& socket) {
socket.setNodelay();
}
})
.configureConnectionOptions({
brynet::net::TcpService::AddSocketOption::WithMaxRecvBufferSize(1024 * 1024),
brynet::net::TcpService::AddSocketOption::AddEnterCallback(enterCallback)
})
.configureListen([=](wrapper::BuildListenConfig config) {
config.setAddr(false, "0.0.0.0", atoi(argv[1]));
})
.asyncRun();

EventLoop mainLoop;
while (true)
Expand Down

0 comments on commit e11fa11

Please sign in to comment.