Files
2025-05-08 15:18:47 +08:00

107 lines
2.7 KiB
C++

#include <string.h>
#include <stdio.h>
#include <mutex>
#include <condition_variable>
#include "workflow/Workflow.h"
#include "workflow/WFTaskFactory.h"
#include "message.h"
using WFTutorialTask = WFNetworkTask<protocol::TutorialRequest,
protocol::TutorialResponse>;
using tutorial_callback_t = std::function<void (WFTutorialTask *)>;
using namespace protocol;
class MyFactory : public WFTaskFactory
{
public:
static WFTutorialTask *create_tutorial_task(const std::string& host,
unsigned short port,
int retry_max,
tutorial_callback_t callback)
{
using NTF = WFNetworkTaskFactory<TutorialRequest, TutorialResponse>;
WFTutorialTask *task = NTF::create_client_task(TT_TCP, host, port,
retry_max,
std::move(callback));
task->set_keep_alive(30 * 1000);
return task;
}
};
int main(int argc, char *argv[])
{
std::mutex mutex;
std::condition_variable cond;
bool finished = false;
unsigned short port;
std::string host;
if (argc != 3)
{
fprintf(stderr, "USAGE: %s <host> <port>\n", argv[0]);
exit(1);
}
host = argv[1];
port = atoi(argv[2]);
std::function<void (WFTutorialTask *task)> callback =
[&host, port, &callback](WFTutorialTask *task) {
int state = task->get_state();
int error = task->get_error();
TutorialResponse *resp = task->get_resp();
char buf[1024];
void *body;
size_t body_size;
if (state != WFT_STATE_SUCCESS)
{
if (state == WFT_STATE_SYS_ERROR)
fprintf(stderr, "SYS error: %s\n", strerror(error));
else if (state == WFT_STATE_DNS_ERROR)
fprintf(stderr, "DNS error: %s\n", gai_strerror(error));
else
fprintf(stderr, "other error.\n");
return;
}
resp->get_message_body_nocopy(&body, &body_size);
if (body_size != 0)
printf("Server Response: %.*s\n", (int)body_size, (char *)body);
printf("Input next request string (Ctrl-D to exit): ");
*buf = '\0';
scanf("%1023s", buf);
body_size = strlen(buf);
if (body_size > 0)
{
WFTutorialTask *next;
next = MyFactory::create_tutorial_task(host, port, 0, callback);
next->get_req()->set_message_body(buf, body_size);
next->get_resp()->set_size_limit(4 * 1024);
**task << next; /* equal to: series_of(task)->push_back(next) */
}
else
printf("\n");
};
/* First request is emtpy. We will ignore the server response. */
WFTutorialTask *task = MyFactory::create_tutorial_task(host, port, 0, callback);
task->get_resp()->set_size_limit(4 * 1024);
Workflow::start_series_work(task, [&mutex, &cond, &finished](const SeriesWork *)
{
mutex.lock();
finished = true;
cond.notify_one();
mutex.unlock();
});
std::unique_lock<std::mutex> lock(mutex);
while (!finished)
cond.wait(lock);
lock.unlock();
return 0;
}