linux socket select 客户端,socket编程(Linux下使用select函数实现多客户端连接服务器)...

#include #define SERVER_PORT 6666

#define BUFES 20

int main(void)

{

int fd_clint;

int n;

struct sockaddr_in clint_addr;

bzero(&clint_addr, sizeof(clint_addr));

clint_addr.sin_family = AF_INET;

clint_addr.sin_port = htons(SERVER_PORT);

clint_addr.sin_addr.s_addr = INADDR_ANY;

fd_clint = socket(AF_INET, SOCK_STREAM, 0);

if(fd_clint < 0)

{

perror("fail to socket\n");

exit(1);

}

if(connect(fd_clint, (struct sockaddr*)&clint_addr, sizeof(clint_addr)) < 0)

{

perror("fail to connect\n");

exit(1);

}

fd_set readfds;

int max_fd = fd_clint + 1;

while(1)

{

FD_ZERO(&readfds);

FD_SET(0, &readfds);

FD_SET(fd_clint, &readfds);

char buf[BUFES];

printf("Please enter command!\n");

if(select(max_fd, &readfds, NULL, NULL, NULL) > 0)

{

if(FD_ISSET(0, &readfds))

{

scanf("%s", buf);

n = send(fd_clint, buf, BUFES, 0);

if(n < 0)

{

perror("send falied\n");

exit(1);

}

}

if(FD_ISSET(fd_clint, &readfds))

{

n = read(fd_clint, buf, BUFES);

if(n == 0)

{

perror("server has closed \n");

exit(1);

}

else if(n < 0)

{

perror("socket failed\n");

exit(1);

}

}

}

}

if(close(fd_clint) < 0)

{

perror("fail to close fd_clint\n");

exit(1);

}

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值