Lao Chen has a daughter who works in the field and can't often come back, Lao Chen and her through letter contact. Their letters will be delivered to their mailboxes by the postman.
This is very similar to the socket model. Below I take old Chen to receive the letter for example to explain the socket I/O model.
One: Select model
Lao Chen is very interested in seeing his daughter's letter. So that he went downstairs every 10 minutes to check the mailbox, to see if there is a daughter's letter, in this case, "downstairs check the mailbox" and then back upstairs delayed old Chen too much time, so old Chen can not do other work.
The Select model is very similar to that of old Chen: Go round and round to check ... If there is data ... Receive/Send ....
Using threads Select should be a common practice:
Procedure Tlistenthread.execute;
Var
Addr:tsockaddrin;
Fd_read:tfdset;
Timeout:ttimeval;
Asock,
Mainsock:tsocket;
Len, I:integer;
Begin
Mainsock: = Socket (af_inet, sock_stream, ipproto_tcp);
addr.sin_family: = af_inet;
Addr.sin_port: = htons (5678);
Addr.sin_addr. S_ADDR: = htonl (Inaddr_any);
Bind (Mainsock, @addr, sizeof (addr));
Listen (Mainsock, 5);
while (don't terminated) do
Begin
Fd_zero (Fd_read);
Fd_set (Mainsock, fd_read);
Timeout.tv_sec: = 0;
Timeout.tv_usec: = 500;
If select (0, @fd_read, nil, nil, @timeout) > 0 then//At least 1 waiting for accept connection
Begin
If Fd_isset (Mainsock, Fd_read) Then
Begin
For i:=0 to Fd_read.fd_count-1 do//note, Fd_count <= 64, which means that select can manage up to 64 connections at the same time
Begin
Len: = sizeof (addr);
Asock: = Accept (Mainsock, addr, Len);
If Asock <> Invalid_socket Then
...//create a new thread for Asock, and then select again in the new thread
End
End
End
End while (not self. Terminated)
Shutdown (Mainsock, sd_both);
Closesocket (Mainsock);
End