Linux源码-TCP网络服务器的实现
/*********************************************ABOUT FILE*********************************************
***File Name:CycleTCPServer
***Purpose: 循环tcp服务端程序
***Note:网络服务器就两大类:循环服务和并发服务。首先,循环网络服务器编程实现的步骤是这样的:这种服务
器模型是典型循环服务,如果不加上多进程/线程技术,此种服务吞吐量有限,大家都可以看到,如果前一个连
接服务数据没有收发完毕后面的连接没办法处理。所以一般有多进程技术,对一个新连接启用一个新进程去处
理,而监听socket继续监听。
***Wrote By: DanyLin
***Date Time: 2013-08-24
***Note: 任何人可以任意复制代码并运用这些文档,当然包括你的商业用途,但请遵循GPL
****************************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
int main(int argc, char ** argv)
{
int sockfd,new_fd;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
unsigned int sin_size, myport, lisnum;
if(argv[1])
myport = atoi(argv[1]);
else
myport = 7838;
if(argv[2])
lisnum = atoi(argv[2]);
else
lisnum = 2;
if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
exit(1);
}
my_addr.sin_family=PF_INET;
my_addr.sin_port=htons(myport);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero), 0);
if(bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1)
{
perror("bind");
exit(1);
}
if (listen(sockfd, lisnum) == -1)
{
perror("listen");
exit(1);
}
while(1)
{
sin_size = sizeof(struct sockaddr_in);
if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1)
{
perror("accept");
continue;
}
printf("server: got connection from %s\n",inet_ntoa(their_addr.sin_addr));
if (!fork())
{
if (send(new_fd, "Hello, world!\n", 14, 0) == -1)
{
perror("send");
close(new_fd);
exit(0);
}
}
close(new_fd);
waitpid(-1,NULL,WNOHANG);
}
}
/*********************************************ABOUT FILE*********************************************
***File Name:CycleTCPClient.c
***Purpose: 简单测试
***Wrote By: DanyLin
***Date Time: 2013-08-24
***Note: 任何人可以任意复制代码并运用这些文档,当然包括你的商业用途,但请遵循GPL
****************************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define MAXDATASIZE 100 /*每次最大数据传输量 */
int main(int argc, char *argv[])
{
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct hostent *he;
struct sockaddr_in their_addr;
unsigned int myport;
if(argv[2])
myport = atoi(argv[2]);
else
myport = 7838;
if (argc != 3)
{
fprintf(stderr,"usage: %s hostname port\n", argv[0]);
exit(1);
}
if((he=gethostbyname(argv[1]))==NULL)
{
herror("gethostbyname");
exit(1);
}
if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
exit(1);
}
their_addr.sin_family=PF_INET;
their_addr.sin_port=htons(myport);
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
bzero(&(their_addr.sin_zero),0);
if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1)
{
perror("connect");
exit(1);
}
if ((numbytes=recv(sockfd, buf, MAXDATASIZE, 0)) == -1)
{
perror("recv");
exit(1);
}
buf[numbytes] = 0;
printf("Received: %s\n",buf);
close(sockfd);
return 0;
}
复制代码用gcc cycletcpserver.c -o tcpserver和gcc cycletcpclient.c -o tcpclient分别编译上述代码后运行情况如下:
服务端运行显示:
dany@dany-virtual-machine:~/ProgTest$ ./tcpserver
server: got connection from 127.0.0.1
server: got connection from 127.0.0.1
server: got connection from 127.0.0.1
客户端运行显示:
dany@dany-virtual-machine:~/ProgTest$ ./tcpclient 127.0.0.1 7838
Received: Hello, world!
dany@dany-virtual-machine:~/ProgTest$ ./tcpclient 127.0.0.1 7838
Received: Hello, world!
dany@dany-virtual-machine:~/ProgTest$ ./tcpclient 127.0.0.1 7838
Received: Hello, world!
不得不说的一个概念性问题:阻塞与非阻塞
/*********************************************ABOUT FILE*********************************************
***File Name:TCPForwardPort.c
***Purpose: 演示IO多路复用的端口转发程序
***Note:在阻塞服务中,当服务器运行到accept语句而没有客户连接服务请求到来,那么会发生什么情况? 这时服
务器就会停止在accept语句上等待连接服务请求的到来;同样,当程序运行到接收数据语句recv时,如果没有
数据可以读取,则程序同样会停止在接收语句上。这种情况称为阻塞(blocking)。但如果你希望服务器仅仅注
意检查是否有客户在等待连接,有就接受连接;否则就继续做其他事情,则可以通过将 socket设置为非阻塞方
式来实现:非阻塞socket在没有客户在等待时就使accept调用立即返回 。通过设置socket为非阻塞方式,可以
实现“轮询”若干socket。当企图从一个没有数据等待处理的非阻塞socket读入数据时,函数将立即返回,并且
返回值置为-1,并且errno置为EWOULDBLOCK。但是这种“轮询”会使CPU处于忙等待方式,从而降低性能。考虑到
这种情况,假设你希望服务器监听连接服务请求的同时从已经建立的连接读取数据,你也许会想到用一个accept
语句和多个recv()语句,但是由于accept及recv都是会阻塞的,所以这个想法显然不会成功。调用非阻塞的
socket会大大地浪费系统资源。而调用select()会有效地解决这个问题,它允许你把进程本身挂起来,而同时使
系统内核监听所要求的一组文件描述符的任何活动,只要确认在任何被监控的文件描述符上出现活动,select()
调用将返回指示该文件描述符已准备好的信息,从而实现了为进程选出随机的变化,而不必由进程本身对输入进
行测试而浪费CPU开销。其次,并发服务器,在上述cycletcpserver.c中,由于使用了fork技术也可以称之为并
发服务器,但这种服务器并不是真正意义上的IO多路复用的并发服务器,并且由于没有处理阻塞问题,实际应用
有各种各样的问题。
下面是一个演示IO多路复用的源程序,是一个端口转发程序,但它的用处相当大,实际应用中的各类代理软件或
端口映射软件都是基于这样的代码的,比如Windows下的WinGate、WinProxy等都是在此基础上实现的。
***Wrote By: DanyLin
***Date Time: 2013-08-24
***Note: 任何人可以任意复制代码并运用这些文档,当然包括你的商业用途,但请遵循GPL
****************************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
static int forward_port;
#undef max
#define max(x,y) ((x) > (y) ? (x) : (y))
static int listen_socket (int listen_port)
{
struct sockaddr_in a;
int s;
int yes;
if ((s = socket (AF_INET, SOCK_STREAM, 0)) < 0)
{
perror ("socket");
return -1;
}
yes = 1;
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *) &yes, sizeof (yes)) < 41.0)
{
perror ("setsockopt");
close (s);
return -1;
}
memset (&a, 0, sizeof (a));
a.sin_port = htons (listen_port);
a.sin_family = AF_INET;
if (bind(s, (struct sockaddr *) &a, sizeof (a)) < 0)
{
perror ("bind");
close (s);
return -1;
}
printf ("accepting connections on port %d\n", (int) listen_port);
listen (s, 10);
return s;
}
static int connect_socket (int connect_port, char *address)
{
struct sockaddr_in a;
int s;
if ((s = socket (AF_INET, SOCK_STREAM, 0)) < 0)
{
perror ("socket");
close (s);
return -1;
}
memset (&a, 0, sizeof (a));
a.sin_port = htons (connect_port);
a.sin_family = AF_INET;
if (!inet_aton(address, (struct in_addr *) &a.sin_addr.s_addr))
{
perror ("bad IP address format");
close (s);
return -1;
}
if (connect(s, (struct sockaddr *) &a, sizeof (a)) < 0)
{
perror ("connect()");
shutdown (s, SHUT_RDWR);
close (s);
return -1;
}
return s;
}
#define SHUT_FD1 { \
if (fd1 >= 0) { \
shutdown (fd1, SHUT_RDWR); \
close (fd1); \
fd1 = -1; \
} \
}
#define SHUT_FD2 { \
if (fd2 >= 0) { \
shutdown (fd2, SHUT_RDWR); \
close (fd2); \
fd2 = -1; \
} \
}
#define BUF_SIZE 1024
int main (int argc, char **argv)
{
int h;
int fd1 = -1, fd2 = -1;
char buf1[BUF_SIZE], buf2[BUF_SIZE];
int buf1_avail, buf1_written;
int buf2_avail, buf2_written;
if (argc != 4)
{
fprintf (stderr, "Usage\n\tfwd \n");
exit (1);
}
signal (SIGPIPE, SIG_IGN);
forward_port = atoi (argv[2]);
/*建立监听socket*/
h = listen_socket (atoi (argv[1]));
if (h < 0)
exit (1);
for (;;)
{
int r, nfds = 0;
fd_set rd, wr, er;
FD_ZERO (&rd);
FD_ZERO (&wr);
FD_ZERO (&er);
FD_SET (h, &rd);
/*把监听socket和可读socket三个一起放入select的可读句柄列表里*/
nfds = max (nfds, h);
if (fd1 > 0 && buf1_avail < BUF_SIZE)
{
FD_SET (fd1, &rd);
nfds = max (nfds, fd1);
}
if (fd2 > 0 && buf2_avail < BUF_SIZE)
{
FD_SET (fd2, &rd);
nfds = max (nfds, fd2);
}
/*把可写socket两个一起放入select的可写句柄列表里*/
if (fd1 > 0 && buf2_avail - buf2_written > 0)
{
FD_SET (fd1, &wr);
nfds = max (nfds, fd1);
}
if (fd2 > 0 && buf1_avail - buf1_written > 0)
{
FD_SET (fd2, &wr);
nfds = max (nfds, fd2);
}
/*把有异常数据的socket两个一起放入select的异常句柄列表里*/
if (fd1 > 0)
{
FD_SET (fd1, &er);
nfds = max (nfds, fd1);
}
if (fd2 > 0)
{
FD_SET (fd2, &er);
nfds = max (nfds, fd2);
}
/*开始select*/
r = select (nfds + 1, &rd, &wr, &er, NULL);
if (r == -1 && errno == EINTR)
continue;
if (r < 0)
{
perror ("select()");
exit (1);
}
/*处理新连接*/
if (FD_ISSET (h, &rd))
{
unsigned int l;
struct sockaddr_in client_address;
memset (&client_address, 0, l = sizeof (client_address));
r = accept (h, (struct sockaddr *)&client_address, &l);
if (r < 0)
{
perror ("accept()");
}
else
{
/*关闭原有连接,把新连接作为fd1,同时连接新的目标fd2*/
SHUT_FD1;
SHUT_FD2;
buf1_avail = buf1_written = 0;
buf2_avail = buf2_written = 0;
fd1 = r;
fd2 = connect_socket (forward_port, argv[3]);
if (fd2 < 0)
{
SHUT_FD1;
}
else
printf ("connect from %s\n", inet_ntoa(client_address.sin_addr));
}
}
/* NB: read oob data before normal reads */
if (fd1 > 0)
{
if (FD_ISSET (fd1, &er))
{
char c;
errno = 0;
r = recv (fd1, &c, 1, MSG_OOB);
if (r < 1)
{
SHUT_FD1;
}
else
{
send (fd2, &c, 1, MSG_OOB);
}
}
}
if (fd2 > 0)
{
if (FD_ISSET (fd2, &er))
{
char c;
errno = 0;
r = recv (fd2, &c, 1, MSG_OOB);
if (r < 1)
{
SHUT_FD1;
}
else
{
send (fd1, &c, 1, MSG_OOB);
}
}
}
/* NB: read data from fd1 */
if (fd1 > 0)
{
if (FD_ISSET (fd1, &rd))
{
r = read (fd1, buf1 + buf1_avail, BUF_SIZE - buf1_avail);
if (r < 1)
{
SHUT_FD1;
}
else
buf1_avail += r;
}
}
/* NB: read data from fd2 */
if (fd2 > 0)
{
if (FD_ISSET (fd2, &rd))
{
r = read (fd2, buf2 + buf2_avail, BUF_SIZE - buf2_avail);
if (r < 1)
{
SHUT_FD2;
}
else
{
buf2_avail += r;
}
}
}
/* NB: write data to fd1 */
if (fd1 > 0)
{
if (FD_ISSET (fd1, &wr))
{
r = write (fd1, buf2 + buf2_written, buf2_avail - buf2_written);
if (r < 1)
{
SHUT_FD1;
}
else
buf2_written += r;
}
}
/* NB: write data to fd1 */
if (fd2 > 0)
{
if (FD_ISSET (fd2, &wr))
{
r = write (fd2, buf1 + buf1_written, buf1_avail - buf1_written);
if (r < 1)
{
SHUT_FD2;
}
else
buf1_written += r;
}
}
/* check if write data has caught read data */
if (buf1_written == buf1_avail)
buf1_written = buf1_avail = 0;
if (buf2_written == buf2_avail)
buf2_written = buf2_avail = 0;
/* one side has closed the connection, keep writing to the other side until empty */
if (fd1 < 0 && buf1_avail - buf1_written == 0)
{
SHUT_FD2;
}
if (fd2 < 0 && buf2_avail - buf2_written == 0)
{
SHUT_FD1;
}
}
return 0;
}
几个常用到的函数
/*********************************************ABOUT FUNC*********************************************
***FUNC Name:select
***Purpose: 此函数的功能是由内核检测在timeout时间内,是否有readfds,writefds,exceptfds三个句柄集(
file descriptors)里的某个句柄(file descriptor)的状态符合寻求,即readfds句柄集里有句柄可读或
writefds句柄集里有可写或exceptfds句柄集里有例外发生,任何一个有变化函数就立即返回,返回值为
timeout发生状态变化的句柄个数。n是所有readfds,writefds,exceptfds三个句柄集(file descriptors)里
编号最大值加1。比如:要检测两个socket句柄fd1和fd2在timeout时间内是否分别可读和可写就可以这样:
先把两个句柄集(file descriptors)清零:
FD_ZERO (&readfds);
FD_ZERO (&writefds);
然后把fd1加入读检测集:
FD_SET (fd1, &readfds);
然后把fd2加入写检测集:
FD_SET (fd2, &writefds);
再给timeout设置值,timeout是这样的一个结构:
struct timeval {
long tv_sec; // seconds
long tv_usec; // microseconds
};
你可以这样赋值:
timeout.tv_sec=1;
timeout.tv_uec=0;
表示检测在1秒钟内是否有句柄状态发生变化。
如果有句柄发生变化,就可以用FD_ISSET检测各个句柄,比如:
FD_ISSET (fd1, &readfds);//检测是否fd1变成可读的了
FD_ISSET (fd2, &writefds);//检测是否fd2变成可写的了
****************************************************************************************************/
typedef struct timeval
{
long tv_sec; // seconds
long tv_usec; // microseconds
};
int select(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
{
fd1 = socket();//创建一个socket
fd2 = socket();//创建一个socket
while(1)
{
FD_ZERO (&readfds);
FD_ZERO (&writefds);
FD_SET (fd1, &readfds);
FD_SET (fd2, &writefds);
timeout.tv_sec=1;
timeout.tv_uec=0;
ret = select(fd1>fd2?(fd1+1):(fd2+1), &readfds, &writefds, NULL, &timeout);
if(ret < 0)
{
printf("系统错误,select出错,错误代码:%d, 错误信息:%s", errno, strerror(errno));
}
else if(ret == 0)
{
printf("select超时返回,没有任何句柄状态发生变化!");
}
//有句柄状态发生了变化
if(FD_ISSET(fd1, &readfds))
{
;//fd1有数据可读;
;//fd1里的数据被读出来;
}
if(FD_ISSET(fd2, &writefds))
{
;//fd2可写;
;//fd2里发送数据给对方;
}
}
}
/*********************************************ABOUT FUNC*********************************************
*** FUNC Name:OpenSCPServer
*** Purpose: 用来建立一个tcp服务端socket
*** Parameter:port整数型监听端口号,total整数型监听个数,sendbuflen整数型发送缓冲区大小recvbuflen整
数型接收缓冲区大小,blockORnot整数型是否阻塞,reuseORnot整数型是否端口重用
*** Note:要使用此函数需要自定义一个全局变量char errorMessage[1024];并包含GetCurrentTime.h头文件
****************************************************************************************************/
int OpenSCPServer(int port, int total, int sendbuflen, int recvbuflen, int blockORnot, int reuseORnot)
{
int sockfd = 0, ret = 0, opt = 0, flags=1;
struct sockaddr_in laddr;
ret = sockfd = socket(PF_INET, SOCK_STREAM, 0);
if(ret < 0)
{
sprintf(errorMessage, "OpenTCPServer socket() error! return:%d, errno=%d, errortext:'%s' %s", ret, errno, strerror(errno), GetCurrentTime(0, 0));
return -1;
}
ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuseORnot, sizeof(int));
if(ret < 0)
{
sprintf(errorMessage, "OpenTCPServer setsockopt() reuse error! return:%d, errno=%d, errortext:'%s' %s", ret, errno, strerror(errno), GetCurrentTime(0, 0));
return -2;
}
ret = setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &recvbuflen, sizeof(int));
if ( ret < 0)
{
sprintf(errorMessage, "OpenTCPServer setsockopt() recvbuf error! return:%d, errno=%d, errortext:'%s' %s", ret, errno, strerror(errno), GetCurrentTime(0, 0));
return -3;
}
ret = setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &sendbuflen, sizeof(int));
if (ret < 0)
{
sprintf(errorMessage, "OpenTCPServer setsockopt() sendbuf error! return:%d, errno=%d, errortext:'%s' %s", ret, errno, strerror(errno), GetCurrentTime(0, 0));
return -4;
}
ioctl(sockfd,FIONBIO,&blockORnot);/*block or not*/
laddr.sin_family = PF_INET;
laddr.sin_port = htons(port);
laddr.sin_addr.s_addr = INADDR_ANY;
bzero(&(laddr.sin_zero), 8);
ret = bind(sockfd, (struct sockaddr *)&laddr, sizeof(struct sockaddr));
if(ret < 0)
{
sprintf(errorMessage, "OpenTCPServer bind() error! return:%d, errno=%d, errortext:'%s' %s", ret, errno, strerror(errno), GetCurrentTime(0, 0));
close(sockfd);
return -5;
}
ret = listen(sockfd, total);
if(ret < 0)
{
sprintf(errorMessage, "OpenTCPServer listen() error! return:%d, errno=%d, errortext:'%s' %s", ret, errno, strerror(errno), GetCurrentTime(0, 0));
close(sockfd);
return -6;
}
sprintf(errorMessage, "OpenTCPServer opened on port.%d(%d) OK, socket(%d), buf(%d:%d)! %s", port, total, sockfd, sendbuflen, recvbuflen, GetCurrentTime(0, 0));
return sockfd;
}
/*********************************************ABOUT FUNC*********************************************
*** FUNC Name:ConnectSCPServer
*** Purpose: 用来建立一个tcp客户端socket
*** Parameter:serverip服务器IP地址或主机名,serverport服务器端口,blockORnot整数型是否阻塞
*** Note:要使用此函数需要自定义一个全局变量char errorMessage[1024];并包含自己编写的GetCurrentTime.h
头文件
****************************************************************************************************/
int ConnectSCPServer(char * serverip, int serverport, int blockORnot)
{
int serversock = 0, ret = 0;
unsigned long addr;
struct sockaddr_in sin;
struct hostent *he;
if((he=gethostbyname(serverip))== 0)
{
sprintf(errorMessage, "ConnectSCPServer IP address '%s' error! return:-1 %s", serverip, GetCurrentTime(0, 0));
return -1;
}
serversock = socket(PF_INET, SOCK_STREAM, 0);
if(serversock == -1) {
sprintf(errorMessage, "ConnectSCPServer socket() error! return:-2, errno=%d, errortext:'%s' %s", errno, strerror(errno), GetCurrentTime(0, 0));
return -2;
}
ioctl(serversock, FIONBIO, &blockORnot); //block or not
memset((char*)&sin, 0, sizeof(struct sockaddr_in));
sin.sin_family = PF_INET;
sin.sin_port = htons(serverport);
sin.sin_addr = *((struct in_addr *)he->h_addr);
ret = connect(serversock, (struct sockaddr *)&sin, sizeof(sin));
if(ret == -1) {
sprintf(errorMessage, "ConnectSCPServer connect() error! return:-3, errno=%d, errortext:'%s' %s", errno, strerror(errno), GetCurrentTime(0, 0));
close(serversock);
return -3;
}
return serversock;
}
/*********************************************ABOUT FUNC*********************************************
*** FUNC Name:Send
*** Purpose: 用来通过一个socket在指定时间内发送数据
*** Parameter:sock整数型socket,buf待发送的内容,size要发送的大小,flag发送选项,timeout超时时间值
*** Note:要使用此函数需要自定义一个全局变量char errorMessage[1024];并包含自己编写的GetCurrentTime.h
头文件
****************************************************************************************************/
int Send(int sock, char * buf, size_t size, int flag, int timeout)
{
int i = 0, ret = 0, intretry = 0;
struct timeval tival;
fd_set writefds;
int maxfds = 0;
tival.tv_sec = timeout;
tival.tv_usec = 0;
FD_ZERO(&writefds);
if(sock > 0) {
FD_SET(sock, &writefds);
maxfds=((sock > maxfds)?sock:maxfds);
}
else {
sprintf(errorMessage, "Send socket:%d error! return:-2 %s", sock, GetCurrentTime(0, 0));
return -2;
}
ret = select(maxfds + 1, NULL, &writefds, NULL, &tival);
if(ret <= 0) {
if(ret < 0)
sprintf(errorMessage, "Send socket:%d select() error! return:%d, errno=%d, errortext:'%s' %s", sock, ret, errno, strerror(errno), GetCurrentTime(0, 0));
else
sprintf(errorMessage, "Send socket:%d select timeout(%d)! %s", sock, timeout, GetCurrentTime(0, 0));
close(sock);
return -3;
}
if(!(FD_ISSET(sock, &writefds))) {
sprintf(errorMessage, "Send socket:%d not in writefds! %s", sock, GetCurrentTime(0, 0));
close(sock);
return -4;
}
while(i < size) {
ret = send(sock, buf + i, size - i, flag);
if(ret <= 0) {
sprintf(errorMessage, "Send socket:%d send() error! return:%d, errno=%d, errortext:'%s' %s", sock, ret, errno, strerror(errno), GetCurrentTime(0, 0));
if (EINTR == errno)
{
if(intretry < 10)
{
intretry++;
continue;
}
else
sprintf(errorMessage, "Send socket:%d send() error!EINTR 10 times! %s", sock, GetCurrentTime(0, 0));
}
close(sock);
return -1;
}
else i += ret;
}
sprintf(errorMessage, "Send socket:%d send() OK! %d/%d bytes sent! %s", sock, i, size, GetCurrentTime(0, 0));
return i;
}
/*********************************************ABOUT FUNC*********************************************
*** FUNC Name:Recv
*** Purpose: 用来从一个socket在指定时间内读取数据
*** Parameter:sock整数型socket,buf接收数据的缓冲区,size要接收数据的大小,flag接收选项,timeout超时
时间值
*** Note:要使用此函数需要自定义一个全局变量char errorMessage[1024];并包含自己编写的GetCurrentTime.h
头文件
****************************************************************************************************/
int Recv(int sock, char * buf, size_t size, int flag, int timeout)
{
int i = 0, ret = 0, intretry = 0;
struct timeval tival;
fd_set readfds;
int maxfds = 0;
tival.tv_sec = timeout;
tival.tv_usec = 0;
FD_ZERO(&readfds);
if(sock > 0)
{
FD_SET(sock, &readfds);
maxfds=((sock > maxfds)?sock:maxfds);
}
else
{
sprintf(errorMessage, "Recv socket:%d error! return:-2 %s", sock, GetCurrentTime(0, 0));
return -2;
}
ret = select(maxfds + 1, &readfds, NULL, NULL, &tival);
if(ret <= 0) {
if(ret < 0)
sprintf(errorMessage, "Recv socket:%d select() error! return:%d, errno=%d, errortext:'%s' %s", sock, ret, errno, strerror(errno), GetCurrentTime(0, 0));
else
sprintf(errorMessage, "Recv socket:%d select timeout(%d)! %s", sock, timeout, GetCurrentTime(0, 0));
close(sock);
return -3;
}
if(!(FD_ISSET(sock, &readfds)))
{
sprintf(errorMessage, "Recv socket:%d not in readfds! %s", sock, GetCurrentTime(0, 0));
close(sock);
return -4;
}
while(i < size)
{
ret = recv(sock, buf + i, size - i, flag);
if(ret <= 0){
sprintf(errorMessage, "Recv socket:%d recv() error! return:%d, errno=%d, errortext:'%s' %s", sock, ret, errno, strerror(errno), GetCurrentTime(0, 0));
if(errno == EINTR)
{
if(intretry < 10)
{
intretry++;
continue;
}
else
sprintf(errorMessage, "Recv socket:%d recv() error! EINTR 10 times! %s", sock, GetCurrentTime(0, 0));
}
close(sock);
return -1;
}
else
i += ret;
}
sprintf(errorMessage, "Recv socket:%d recv() OK! %d/%d bytes received! %s", sock, i, size, GetCurrentTime(0, 0));
return i;
}
最后需要说明的是:我这里讲到的源程序并不能实际地作为一个产品程序来用,实际情况下可能会有其它许多工作要做,比如可能要建立共享队列来存放 socket里读到的消息,也可能把发送消息先进行排队然后再调用Send函数。还有,如果不是全数字,在发送前一定要htonl转换为网络字节序,同理接收到后一定要先ntohl由网络字节序转换为主机字节序,否则对方发送过来的0x00000001在你这里可能是0x00010000,因为高低位顺序不同