服务器端:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<sys/mman.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include<sys/socket.h>
#include<fcntl.h>
#include<errno.h>
//服务端程序
//定义包头
struct packet
{
int len;
char buf[1024];
};
//因为read函数每次读取的字节数长度不确定,所以我们封装一个函数
//让函数每次都读取确定大小的字节数
ssize_t readn(int fd, void *buf, size_t count)
{
//我要接收count个字节数
size_t nleft = count;//还剩下的需要读取的字节数
ssize_t nread;//已经接收的字节数
char *bufp = (char*)buf;
while(nleft >0)//只要还有字节没接收
{
if( ( nread = read(fd, bufp, nleft) ) < 0 )
{
if(errno == EINTR)//被信号中断,不退出,继续接收
continue;
else
return -1;
}
else if(nread == 0)//对等方关闭了
{
return count - nleft;
}
bufp += nread;
nleft -= nread;
}
return count - nleft ;
}
ssize_t writen(int fd, const void *buf, size_t count)
{
//我要发送count个字节数
size_t nleft = count;//还剩下的需要发送的字节数
ssize_t nwritten;//已经发送的字节数
char *bufp = (char*)buf;
while(nleft >0)
{
if( ( nwritten = write(fd, bufp, nleft) ) < 0 )
{
if(errno == EINTR)//被信号中断,不退出,继续接收
continue;
else
return -1;
}
else if(nwritten == 0)//对等方关闭了
{
continue;
}
bufp += nwritten;
nleft -= nwritten;
}
return count - nleft