Encapsulate a simple network library on libevent to facilitate the construction of TCP/UDP/UNIX servers and clients.
Interface example:
int ts_accept_fun(int sfd, int cfd, struct sockaddr *addr, int addrLen)
{
fprintf(stderr, "[srv] accept srv_fd: %d, cli_fd: %d, addrLen: %dn", sfd, cfd, addrLen);
return 0;
}
// pkg is a complete application layer protocol package, headCmd is used by the client to indicate the pkg unpacking protocol
int ts_pkg_fun(int sock, struct sockaddr *addr, unsigned int addrLen, const char *pkg, unsigned int pkgLen, unsigned int headCmd)
{
fprintf(stderr, "[srv] sock: %d, pkg: %s, pkg_len: %d, head_cmd: %dn", sock, pkg, pkgLen, headCmd);
return 0;
}
int ts_close_fun(int sock)
{
fprintf(stderr, "[srv] cli sock: %d closen", sock);
return 0;
}
int ts_timer_fun()
{
fprintf(stderr, "[srv] timer exec, time: %dn", time(NULL));
return 0;
}
void test_tcp_srv()
{
const char *ip = "127.0.0.1";
unsigned int port = 1235;
ev_srv_init(&evSrv);
int iRet = ev_srv_bind_ip(&evSrv, ip, port, ts_accept_fun, ts_pkg_fun, ts_close_fun, 0, -1, 5);
YG_ASSERT_RET(iRet > 0, );
iRet = ev_srv_add_timer(&evSrv, ts_timer_fun, 1000 * 3);
YG_ASSERT_RET(iRet >= 0, );
ev_srv_run(&evSrv);
}
test: