服務端初始化:
socket();
bind();
listen();
for( ; ; )
fd_set(listen_fd , &allset);//設定監聽讀寫檔案描述符
select();//呼叫select函式
if()//如果是傾聽套接字就緒,說明乙個新的連線請求建立
建立連線(accept);
加入到監聽檔案描述符中去;
else//否則說明是乙個已經連線過的描述符
進行操作(read或者write);
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define serv_port 9888
#define wait_count 5
#define read_size 32
//void send_myself(int fd);
//void *pthread_handle(void *arg);
int main(int argc, char **argv)
max_i = -1;
max_fd = listen_fd;
bzero(&listen_addr,sizeof(listen_addr));
listen_addr.sin_family = af_inet;
listen_addr.sin_addr.s_addr = htonl(inaddr_any);
listen_addr.sin_port = htons(serv_port);
bind(listen_fd,(struct sockaddr *)&listen_addr,len);
listen(listen_fd,wait_count);
for(i = 0; i < fd_setsize; ++i)
client[i] = -1;
fd_zero(&allset);
for(;;)
for(i = 0; i < fd_setsize; ++i)
}if(fd_setsize == i)
fd_set(conn_fd,&allset);/*add new descriptor to allset*/
if(conn_fd > max_fd)
max_fd = conn_fd;
if(i > max_i)
max_i = i;
if(--nready <= 0)
continue;
}else
;int size = read(sock_fd,tmp,read_size-1);
write(stdout_fileno,tmp,size);
bzero(tmp,read_size);
fd_clr(sock_fd,&allset);
close(sock_fd);
client[i] = -1;
continue;
//if(--nready <= 0)
//break;
}}}}return 0;}/*
void *pthread_handle(void *arg)
*//*
void send_myself(int fd)
;char *p_tmp = tmp;
while(1)
if(0 == write(fd,tmp,size))
bzero(tmp,read_size);}}
*/
Select實現併發伺服器
併發伺服器除了可以用多執行緒和多程序實現以外,還可以用select實現單執行緒併發,下面用select實現簡單的示例,伺服器接收客戶端的連線,並將客戶發的訊息返回,如下 伺服器端 main.c include include include include include include inclu...
TCP服務端實現併發
socket 在 tcp 協議下通訊 客戶端import socket 建立客戶端tcp協議通訊 c socket.socket 與指定服務端握手 c.connect 127.0.0.1 8080 通訊迴圈 while true 向服務端傳送資訊 msg input if len msg 0 con...
TCP伺服器實現epoll併發實現
原始碼在最下方 併發伺服器 tcp伺服器百萬級連線 申請乙個int sockfd socket af inet,sock stream,0 初始化乙個例項sockaddr in struct sockaddr in addr memset addr,0,sizeof struct sockaddr ...