103 Star 822 Fork 259

GVPlibhv / libhv

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
TcpServer_test.cpp 1.91 KB
一键复制 编辑 原始数据 按行查看 历史
ithewei 提交于 2022-07-20 20:51 . #221: save host and port for restart
/*
* TcpServer_test.cpp
*
* @build make evpp
* @server bin/TcpServer_test 1234
* @client bin/TcpClient_test 1234
*
*/
#include <iostream>
#include "TcpServer.h"
using namespace hv;
#define TEST_TLS 0
int main(int argc, char* argv[]) {
if (argc < 2) {
printf("Usage: %s port\n", argv[0]);
return -10;
}
int port = atoi(argv[1]);
hlog_set_level(LOG_LEVEL_DEBUG);
TcpServer srv;
int listenfd = srv.createsocket(port);
if (listenfd < 0) {
return -20;
}
printf("server listen on port %d, listenfd=%d ...\n", port, listenfd);
srv.onConnection = [](const SocketChannelPtr& channel) {
std::string peeraddr = channel->peeraddr();
if (channel->isConnected()) {
printf("%s connected! connfd=%d id=%d tid=%ld\n", peeraddr.c_str(), channel->fd(), channel->id(), currentThreadEventLoop->tid());
} else {
printf("%s disconnected! connfd=%d id=%d tid=%ld\n", peeraddr.c_str(), channel->fd(), channel->id(), currentThreadEventLoop->tid());
}
};
srv.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) {
// echo
printf("< %.*s\n", (int)buf->size(), (char*)buf->data());
channel->write(buf);
};
srv.setThreadNum(4);
srv.setLoadBalance(LB_LeastConnections);
#if TEST_TLS
hssl_ctx_opt_t ssl_opt;
memset(&ssl_opt, 0, sizeof(hssl_ctx_opt_t));
ssl_opt.crt_file = "cert/server.crt";
ssl_opt.key_file = "cert/server.key";
ssl_opt.verify_peer = 0;
srv.withTLS(&ssl_opt);
#endif
srv.start();
std::string str;
while (std::getline(std::cin, str)) {
if (str == "close") {
srv.closesocket();
} else if (str == "start") {
srv.start();
} else if (str == "stop") {
srv.stop();
break;
} else {
srv.broadcast(str.data(), str.size());
}
}
return 0;
}
C++
1
https://gitee.com/libhv/libhv.git
git@gitee.com:libhv/libhv.git
libhv
libhv
libhv
master

搜索帮助