原生的API中沒有進行錯誤處理以及讀寫控制,在此我們將其封裝:
#pragma once
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
#include <cstdio>
#include <error.h>
#include <zconf.h>
namespace wrap
{
void wrap_perr_exit(const char* str)
{
perror(str);
exit(1);
}
int wrap_accept(int fd, struct sockaddr *sockaddr_, socklen_t *socklen_)
{
while (true)
{
int n = accept(fd, sockaddr_, socklen_);
if(n < 0)
{
if( (errno == ECONNABORTED) || (errno == EINTR))
continue;
else
perror("accept error");
}
else
return n;
}
}
void wrap_bind(int fd, const struct sockaddr *sockaddr_, socklen_t socklen_)
{
if(bind(fd, sockaddr_, socklen_) < 0)
perror("bind error");
}
void wrap_connect(int fd, const struct sockaddr *sockaddr_, socklen_t socklen_)
{
if(connect(fd, sockaddr_, socklen_) < 0)
perror("connect error");
}
void wrap_listen(int fd, int backlog)
{
if(listen(fd, backlog) < 0)
perror("listen error");
}
int wrap_socket(int family, int type, int protocol)
{
int n = socket(family, type, protocol);
if(n < 0)
perror("socket error");
return n;
}
ssize_t wrap_read(int fd, void *ptr, size_t n_bytes)
{
while (true)
{
ssize_t n = read(fd, ptr, n_bytes);
if(n == -1)
{
if(errno == EINTR)
continue;
else
return -1;
}
else
return n;
}
}
ssize_t wrap_write(int fd, const void *ptr, size_t n_bytes)
{
while(true)
{
ssize_t n = write(fd, ptr, n_bytes);
if(n == -1)
{
if(errno == EINTR)
continue;
else
return -1;
}
else
return n;
}
}
void wrap_close(int fd)
{
int n = close(fd);
if(n == -1)
perror("close error");
}
ssize_t wrap_read_n(int fd, void *vptr, size_t n)
{
size_t nleft = n;
ssize_t nread;
auto ptr = (char*) vptr;
while(nleft > 0)
{
nread = read(fd, ptr, nleft);
if(nread < 0)
{
if(errno == EINTR)
nread = 0;
else
return -1;
}
else if(nread == 0)
break;
nleft -= nread;
ptr += nread;
}
return n - nleft;
}
ssize_t wrap_write_n(int fd, const void *vptr, size_t n)
{
size_t nleft = n;
ssize_t nwritten;
const char *ptr = (const char*) vptr;
while(nleft > 0)
{
nwritten = write(fd, ptr, nleft);
if(nwritten <= 0)
{
if(nwritten < 0 && errno == EINTR)
nwritten = 0;
else
return -1;
}
nleft -= nwritten;
ptr += nwritten;
}
return n;
}
}