client 和 server 通讯实例(TCP协议使用 select 函数)
先用标准输入(键盘输入)演示 select 函数的使用:
/****** sample.c for Linux ******/
#include <stdio.h>
#include <string.h>
#include <sys/select.h>
#define STDIN 0
int main()
{
int n, flag;
char buf[80];
fd_set fds;
struct timeval tv;
int fd = STDIN;
printf("type \"eXit\" to exit.\n");
flag = 1;
while(1 == flag)
{
tv.tv_sec=10;
tv.tv_usec=0;
FD_ZERO(&fds);
FD_SET(fd,&fds);
//[] switch(select(fd+1, &fds, NULL, NULL, &tv))
switch(select(FD_SETSIZE, &fds, NULL, NULL, &tv))
{
case -1: // select错误
printf("返回错误。\n");
flag = -1;
break;
case 0: //再次轮询
printf("超时。\n");
break;
default:
if(FD_ISSET(fd, &fds))
{
fgets(buf, 20, stdin);
n = strlen(buf);
if('\n' == buf[n-1])
buf[n-1] = '\0';
printf("数据:%s\n", buf);
if(0 == strcmp(buf, "eXit")) //退出程序?
{
flag = 0;
break;
}
}
break;
}
}
return flag;
}
执行结果示例:
[root@localhost ~]# ./sample
type "eXit" to exit.
asdf
数据:asdf
asdfg
数据:asdfg
sdf
数据:sdf
超时。
超时。
eXit
数据:eXit
[root@localhost ~]#
服务器端代码(Linux系统,TCP协议):
/****** server.c for Linux ******/
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define STDIN 0
int main(int argc, char *argv[])
{
int n, flag;
char buf[1024];
fd_set fds;
struct timeval tv;
struct sockaddr_in client_addr;
int sockfd, fd, sin_size;
int port;
struct sockaddr_in addr;
int fdstd = STDIN;
if(argc