Total contact of socket I/O model based on Delphi

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.