<title>TCP/IP network programming (transcription Note 5) –select and IO multiplexing</title> TCP/IP network programming (transcription Note 5) –select and IO multiplexing
Using fork () to generate a child process can reach a server-side request that can respond to multiple clients at the same time, but this has drawbacks:
Requires a lot of computing and memory space, each process must have a separate memory space, data exchange is also cumbersome (IPC, such as pipelines)
IO Multiplexing:
Ethernet bus structure is also used multiplexing technology, if not adopted, then 22 will be directly communication network knowledge
int Server_sock;int Client_sock;struct sockaddr_in server_addr;struct sockaddr_in client_addr;socklen_t client_size; server_sock = socket (af_inet, sock_stream, 0); memset (&server_addr, 0,sizeof(SERVER_ADDR)); server_addr.sin_family = Af_inet;server_addr.sin_addr.s_addr = htonl (inaddr_any); server_addr.sin_port = Htons (Atoi ( ARGV[1]); Bind (Server_sock, (struct sockaddr*) &server_addr,sizeof(SERVER_ADDR)); Listen (Server_sock, 5);Fd_set reads;Fd_set Read_init;int Fd_max;int Fd_num;struct Timeval Timeout;Char buf[Buf_size+1];int Str_len; fd_max = Server_sock; Fd_zero (&read_init); Fd_set (Server_sock, &read_init); while(1) {reads = Read_init; Timeout.tv_sec = 5; timeout.tv_usec = 0; Fd_num = Select (fd_max+1, &reads, 0, 0, &timeout);if(Fd_num < 0) {// Select Error Break; }Else if(Fd_num = = 0) {printf ("Timeout ...\N");Continue; } for(int I= 0; i < fd_max+1; i++) {if(Fd_isset (i, &reads)) {if(Server_sock = = i) {// indicates that a client initiated a connection requestClient_size =sizeof(CLIENT_ADDR); Client_sock = Accept (Server_sock, (struct sockaddr*) &client_addr, &client_size); Fd_set (Client_sock, &read_init);if(Fd_max < Client_sock) {Fd_max = Client_sock; } printf ("Client Connect:%d\N", Client_sock); }Else{// indicates that a client sent a message.Str_len = Read (I, buf, buf_size); Buf[str_len] = 0;if(Str_len = = 0) {FD_CLR (i, &read_init); Close (i); printf"Client closed:%d\N", i); }Else{Write (I, buf, Str_len); }}}}}close (Server_sock); close (Client_sock);
TCP/IP network programming (transcription Note 5)-Select and IO multiplexing