#include#include #include #include #include #include "server_network.h"int sock_setnonblock(sock_t s){ int flags = 0; flags = fcntl(s, F_GETFL); if (flags < 0) return flags; flags |= O_NONBLOCK; if (fcntl(s, F_SETFL, flags) < 0) return -1; return 0;}int sock_unsetnonblock(sock_t s){ int flags = 0; flags = fcntl(s, F_GETFL); if (flags < 0) return flags; flags &= ~O_NONBLOCK; if (fcntl(s, F_SETFL, flags) < 0) return -1; return 0;}int sock_setnodelay(sock_t s){ int flag =1; return setsockopt(s, SOL_TCP, TCP_NODELAY, (char *)&flag, sizeof(flag));}int sock_set_recv_timeout(sock_t s, int sec){ struct timeval timeout; timeout.tv_sec = sec; timeout.tv_usec = 0; return setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)); }int sock_set_snd_timeout(sock_t s, int sec){ struct timeval timeout; timeout.tv_sec = sec; timeout.tv_usec = 0; return setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout));}int sock_set_keepalive(sock_t s, int timeout){ int val = 1; //设置成keepalive模式 if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)) < 0) { return -1; } //设置探测时间 val = timeout; if (setsockopt(s, SOL_TCP, TCP_KEEPIDLE, &val, sizeof(val)) < 0) { return -1; } //设置探测间隔时间,1s val = 1; if (setsockopt(s, SOL_TCP, TCP_KEEPINTVL, &val, sizeof(val)) < 0) { return -1; } //设置探测次数,3次 val = 3; if (setsockopt(s, SOL_TCP, TCP_KEEPCNT, &val, sizeof(val)) < 0) { return -1; } return 0;}