libhv/include/libhv_server_tcp.hpp

78 lines
2.1 KiB
C++

#pragma once
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include "common.h"
#include "hv/TcpServer.h"
#include "hv/htime.h"
class HvServer {
public:
void Log(const std::string &str) {
std::string log = gxt::format("[SERVER {}]: ", port_);
std::cout << log << str << std::endl;
}
HvServer(int port, std::function<void(std::string &)> fun = {}) {
port_ = port;
server = std::make_unique<hv::TcpServer>();
int listenfd = server->createsocket(port);
if (listenfd < 0) {
Log("createsocket error");
return;
}
std::string logstr = "server listen on port " + std::to_string(port_) +
", listenfd " + std::to_string(listenfd);
Log(logstr);
server->onConnection = [&](const hv::SocketChannelPtr &channel) {
std::string peeraddr = channel->peeraddr();
if (channel->isConnected()) {
char buffer[256] = {0};
sprintf(buffer, "%s connected! connfd=%d\n", peeraddr.c_str(),
channel->fd());
Log(std::string(buffer));
} else {
char buffer[256] = {0};
sprintf(buffer, "%s disconnected! connfd=%d\n", peeraddr.c_str(),
channel->fd());
Log(std::string(buffer));
}
};
// server->onMessage = [&](const hv::SocketChannelPtr &channel,
// hv::Buffer *buf) { OnMessage(channel, buf); };
server->onMessage = [&, fun](const hv::SocketChannelPtr &channel,
hv::Buffer *buf) {
if (fun) {
std::string msg((char *)buf->data());
fun(msg);
} else {
OnMessage(channel, buf);
}
};
server->setThreadNum(4);
server->start();
Log("start server");
}
void Stop() {
if (server) {
server->stop();
}
}
private:
void OnMessage(const hv::SocketChannelPtr &channel, hv::Buffer *buf) {
std::string msg((char *)buf->data());
Log(msg);
// server->broadcast(msg); // 用于广播回所有的连接客户端
}
int port_;
std::unique_ptr<hv::TcpServer> server;
};