|
我现在实现个网络server有这样的需求, 一般情况下是 从客户端读数据的, 但是有时候需要往客户端主动去写数据,我想到了用select.
select的原型是 ( nfds, readfds, writefds, errorfds, time)是这样的, 看这个是能够同时处理 read和write的同时访问,
但我无论是 书上 和网络上,查了一下,select的一般例子都是 用于多客户端读的情况, 基本代码如下:
- server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
- server_address.sin_family = AF_INET;
- server_address.sin_addr.s_addr = htonl(INADDR_ANY);
- server_address.sin_port = htons(9734);
- server_len = sizeof(server_address);
- bind(server_sockfd, (struct sockaddr *)&server_address, server_len);
- /* Create a connection queue and initialize readfds to handle input from server_sockfd. */
- listen(server_sockfd, 5);
- FD_ZERO(&readfds);
- FD_SET(server_sockfd, &readfds);
- /* Now wait for clients and requests.
- Since we have passed a null pointer as the timeout parameter, no timeout will occur.
- The program will exit and report an error if select returns a value of less than 1. */
- while(1) {
- char ch;
- int fd;
- int nread;
- testfds = readfds;
- printf("server waiting\n");
- result = select(FD_SETSIZE, &testfds, (fd_set *)0,
- (fd_set *)0, (struct timeval *) 0);
- if(result < 1) {
- perror("server5");
- exit(1);
- }
- /* Once we know we've got activity,
- we find which descriptor it's on by checking each in turn using FD_ISSET. */
- for(fd = 0; fd < FD_SETSIZE; fd++) {
- if(FD_ISSET(fd,&testfds)) {
- /* If the activity is on server_sockfd, it must be a request for a new connection
- and we add the associated client_sockfd to the descriptor set. */
- if(fd == server_sockfd) {
- client_len = sizeof(client_address);
- client_sockfd = accept(server_sockfd,
- (struct sockaddr *)&client_address, &client_len);
- FD_SET(client_sockfd, &readfds);
- printf("adding client on fd %d\n", client_sockfd);
- }
- /* If it isn't the server, it must be client activity.
- If close is received, the client has gone away and we remove it from the descriptor set.
- Otherwise, we 'serve' the client as in the previous examples. */
- else {
- ioctl(fd, FIONREAD, &nread);
- if(nread == 0) {
- close(fd);
- FD_CLR(fd, &readfds);
- printf("removing client on fd %d\n", fd);
- }
- else {
- read(fd, &ch, 1);
- sleep(5);
- printf("serving client on fd %d\n", fd);
- ch++;
- write(fd, &ch, 1);
- }
- }
- }
- }
- }
复制代码
那想请教如何用select实现 读写都可以呢? |
阿莫论坛20周年了!感谢大家的支持与爱护!!
一只鸟敢站在脆弱的枝条上歇脚,它依仗的不是枝条不会断,而是自己有翅膀,会飞。
|