加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
Socket.cpp 1.94 KB
一键复制 编辑 原始数据 按行查看 历史
leo_1 提交于 2023-10-19 09:09 . 添加acceptor
/***
* @Description:
* @Author: LeoTao
* @Date: 2023-10-17 23:10:38
* @LastEditTime: 2023-10-18 04:05:57
*/
#include "Socket.h"
#include "InetAddress.h"
#include "logger.h"
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
Socket::~Socket(){
close(sockfd_);
}
void Socket::bindAddress(const InetAddress& localaddr){
int ret = ::bind(sockfd_,(sockaddr*)localaddr.getSockAddr(),sizeof(sockaddr_in));
if(ret < 0){
LOG_FATAL("socket:%d bind failed! errno = %d", sockfd_, errno);
}
}
void Socket::listen(){
int ret = ::listen(sockfd_,SOMAXCONN);
if(ret < 0){
LOG_FATAL("socket:%d listen failed! errno = %d", sockfd_, errno);
}
}
int Socket::accept(InetAddress* peeraddr){
struct sockaddr_in addr;
bzero(&addr,sizeof(addr));
socklen_t addrlen = static_cast<socklen_t>(sizeof addr);
int connfd = ::accept(sockfd_,(sockaddr*)&addr, &addrlen);
if(connfd >= 0){
peeraddr->setSockAddr(addr);
}
return connfd;
}
void Socket::shutdownWrite(bool on){
if(shutdown(sockfd_, SHUT_WR) < 0){
LOG_ERROR("sockets::shutdownWrite");
}
}
void Socket::setTcpNoDelay(bool on){
int optval = on ? 1 : 0;
::setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof(optval));
}
void Socket::setReuseAddr(bool on){
int optval = on ? 1 : 0;
::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR,
&optval, static_cast<socklen_t>(sizeof optval));
}
void Socket::setReusePort(bool on){
int optval = on ? 1 : 0;
int ret = ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEPORT,
&optval, static_cast<socklen_t>(sizeof optval));
if (ret < 0 && on)
{
LOG_ERROR("SO_REUSEPORT failed");
}
}
void Socket::setKeepAlive(bool on){
int optval = on ? 1 : 0;
::setsockopt(sockfd_, SOL_SOCKET, SO_KEEPALIVE,
&optval, static_cast<socklen_t>(sizeof optval));
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化