#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
typedef
struct
st_fd_def;
/* 將fd接收套接字描述符放入到fd陣列中
*/int
add_fd
(st_fd_def* p_st_fd,
int fd)
memcpy
(p_fd, p_st_fd->fd,
sizeof
(int
)*p_st_fd->count)
;free
(p_st_fd->fd)
; p_st_fd->fd = p_fd;
p_st_fd->max_count +=3
;}p_st_fd->fd[p_st_fd->count++
]= fd;
printf
("fd=%d, count===%d, max_count===%d\n"
, fd, p_st_fd->count, p_st_fd->max_count)
;return0;
}int
get_max_fd
(st_fd_def* p_st_fd, fd_set* p_fs)
}return max_fd;
}int
remove_fd
(st_fd_def* p_st_fd,
int fd)}}
} p_st_fd->count--
;return i;
}int
destroy_fd
(st_fd_def* p_st_fd)
return0;
}void
*thread_fun
(void
* arg)
//申請3個fd陣列個數
p_st_fd->fd =
(int*)
calloc(3
,sizeof
(int))
;if(p_st_fd->fd ==
null
) p_st_fd->count =0;
p_st_fd->max_count =3;
max_fd =
get_max_fd
(p_st_fd,
&fs)
; tv.tv_sec =2;
tv.tv_usec =0;
fd_zero
(&fs)
;while
(res =
select
(max_fd+1,
&fs,
null
,null
,&tv)
>=0)
printf
("server read socket[%d] data is [%s]\n"
, p_st_fd->fd[index]
, szbuff)
;write
(p_st_fd->fd[index]
, szbuff,
strlen
(szbuff));
}}}//由於服務端不斷在接收新的連線,所以需要重複獲取最大描述符
max_fd =
get_max_fd
(p_st_fd,
&fs);}
}int
main
(int argc,
char
* ar**)
server_fd =
socket
(af_inet, sock_stream,0)
;if(server_fd <0)
/* 埠重複利用 */
setsockopt
(server_fd, sol_socket, so_reuseaddr,
(void*)
&opt,
sizeof
(opt));
serveraddr.sin_family = af_inet;
serveraddr.sin_port =
htons
(atoi
(ar**[1]
)); serveraddr.sin_addr.s_addr = inaddr_any;
res =
bind
(server_fd,
(struct sockaddr*
)&serveraddr,
sizeof
(struct sockaddr));
if(res !=0)
res =
listen
(server_fd,10)
;if(res !=0)
clientaddr_len =
sizeof
(struct sockaddr_in);/*
執行緒函式中呼叫select,主線程用於接收客戶端請求
*/pthread_attr_t attr;
pthread_attr_init
(&attr)
;pthread_attr_setdetachstate
(&attr, pthread_create_detached)
;pthread_create
(&tid,
null
, thread_fun,
(void*)
&st)
;pthread_attr_destroy
(&attr)
;while(1
)// 將接收的client_fd描述符放置到描述符陣列中
add_fd
(&st, client_fd);}
close
(server_fd)
;return0;
}
編譯:gcc server_select.c -o server_select -lpthread
./server_select 8888
結果:fd=4, count=1, max_count=3
fd=5, count=2, max_count=3
fd=6, count=3, max_count=3
fd=7, count=4, max_count=6
max_fd=7
server read socket[4] data is [aaa]
max_fd
=7server read socket[5] data is [aaa]
max_fd=7
server read socket[6] data is [aaa]
max_fd
=7server read socket[7] data is [aaa]
max_fd=7
read socket[4] closed
max_fd
=7read socket[5] closed
max_fd=7
read socket[6] closed
max_fd
=7read socket[7] closed
Linux網路程式設計之select
使用select多路復用技術的非阻塞模型 select多路復用通常具有很好的跨平台性,也能提供不錯的併發效能,但是在通常情況下有最大監聽檔案描述符的限制 通常1024 如果不需要達到c10k這種前端高效能伺服器的要求,採用select nonblocking的方式能降低程式設計的難度 用到的介面 f...
Linux網路程式設計 select函式詳解
作用 select函式是用來監視乙個或多個檔案控制代碼的狀態變化的,可阻塞也可不阻塞。函式原型 int select int nfds,fd set readfds,fd set writefds,fd set exceptfds,struct timeval timeout 函式引數意義 fd m...
Linux 下網路程式設計中的select
include include int select int maxfdp1,fd set readset,fd set writeset,fd set exceptset,const struct timeval timeout return 0 就緒描述字的正數目 1 出錯 0 超時 struc...