Winsock study NOTE 2: wsaasyncselect Model
There are five types of socket I/O models for Winsock applicationsProgramManage I/O, including:Select, wsaasyncselect, wsaeventselect, overlapped, and completion port). Wsaasyncselect (asynchronous selection) is the simplest and best-understood mode, because you do not need to understand the multi-thread programming knowledge in this mode ~
Let's not talk much about it.Code(The following Code does not include Exception Handling. It is only used for learning ):
// Define a message in the unit header first
Const
Wm_socket = Wm_user + 55 ;
//Then define the Message Processing Function
Procedure wmsocket (var msg: tmessage); message wm_socket;
Procedure tform1.formcreate (Sender: tobject );
VaR
Wsdata: wsadata;
Serversocket: tsocket;
Localaddr: tsockaddrin;
Begin
//Initialize Winsock
Wsastartup ($202, Wsdata );
//Create socket
Serversocket:=Socket (af_inet, sock_stream, ipproto_tcp );
// Set localaddr Parameters
Localaddr. sin_family: = Af_inet; // IPv4
Localaddr. sin_addr.s_addr: = Inet_addr ( ' 127.0.0.1 ' ); // Point string format IP address to Internet format
Localaddr. sin_port: = Htons ( 1077 ); // Host to net short, host byte order to network byte order
// Bind the local IP address and port. Set the localaddr parameters before binding.
BIND (serversocket, localaddr, sizeof (localaddr ));
//Set Winsock I/O mode
Wsaasyncselect (serversocket, handle, wm_socket, fd_accept or fd_read );
//Start listening. A maximum of five connections can be monitored at the same time.
Listen (serversocket,5);
End;
Procedure tform1.wmsocket (var msg: tmessage );
VaR
Buff: array [ 0 .. 10 ] Of char;
Addrin: tsockaddrin;
Addrlen: integer;
Clientsocket: tsocket;
Begin
Case Wsagetselectevent (msg. lparam)
Fd_accept: // Receive Connection Request
Begin
Addrlen: = Sizeof (addrin );
Clientsocket: = Accept (msg. wparam, @ addrin, @ addrlen );
Wsaasyncselect (clientsocket, handle, wm_socket, fd_accept or fd_read );
End;
Fd_read: // When a message is sent from the client
Begin
Recv (msg. wparam, buff, sizeof (buff ), 0 );
Memo1.lines. Add (buff );
Buff: = ' I already ed! ' ;
Send (msg. wparam, buff, sizeof (buff ), 0 );
End;
End;
End;
Some descriptions of wsaasyncselect:
1. If this mode is used, your program must have a Windows form;
2. First, you need to define a message. When there is an "Action" on the connection (depending on the action you set during wsaasyncselect), your form will receive the message;
3. msg. wparam indicates the connection, and MSG. lparam indicates the "Action" (read, write, close, connection, etc );
4. The fourth parameter table of wsaasyncselect describes the actions that can be monitored. fd_accept, fd_read, fd_write, and fd_close are commonly used;
Original article: http://blog.csdn.net/dropme/archive/2009/09/08/4532308.aspx