Windows Sockets perform I/O operations in both modes, blocking mode and non-blocking mode. In blocking mode, the function that executes the operation will wait and will not return immediately, until the data is sent or received. This is a waste of performance under certain conditions. For example, when the recvfrom function does not receive data, it will keep waiting.
To improve system performance, Winsock provides message-based asynchronous socket. The following describes the main socket asynchronous communication functions.
<1> int wsasyncselect (socket S, hwnd, unsigned int umsg, longlevent );
This function registers a Levent event. When a Levent event is triggered (for example, when fd_read is registered, once data is sent, the Levent event is triggered ), the system will send an umsg message, and the sending window is the window pointed to by the hwnd handle.
<2> int wsaenumprotocols (lpint lpiprotocols, lpwsaprotocol_infolpprotocolbuffer, ilpdword lpdwbufferlength );
Lpiprotocols: Array of protocol identifiers ending with null. this parameter is optional. If lpiprotocols is null, the function returns information about all available protocols. Otherwise, only the protocol information listed in the array is returned.
Lpprotocolbuffer: Out type data, used as the return value, a buffer filled with wsaprotocol_info struct. This struct stores the complete information of a specified protocol.
Lpdwbufferlength: In/out type parameter. During input, specify the length passed to the lpprotocolbuffer buffer. During output, obtain the minimum buffer length of all access request information passed to the wsaenumprotocols function.
<3> int wsasocket (int af, int type, intprotocol, lpwsaprotocol_info, lpprotocolinfo, group G, DWORD dwflags );
Lpprotocolinfo: Pointer to the wsaprotocol_info struct, which specifies the feature of the created socket. If lpprotocolinfo is null, Win32 DLL uses the first three parameters to determine which service provider to use.
G: Reserved
Dwflags: Specifies the description of the socket property. If this parameter is wsa_flag_overlapped, an overlapping socket is created.
<4> int wsarecvfrom (socket S, blocks, DWORD dwbuffercount, lpdword blocks, lpdwordlpflags, sockaddr * lpfrom, lpint lpfromlen, lpwsaoverlapped lpoverlapped, callback );
Lpbuffers: In/out type parameter, a pointer to the wsabuf struct array, which is defined as follows:
typedef struct _WSABUF{u_long len;char *buf;}WSABUF,*LPWSABUF;
It can be seen that this struct refers to the buffer and length of the received data.
Dwbuffercount: Number of wsabuf struct in the array to which lpbuffers points.
Lpnumberofbytesrecvd: Out type parameter. If the accept operation is completed immediately, this parameter points to the number of bytes accepted in this call.
Lpflags: In/out type parameter, a pointer to a flag.
Lpfrom: An out pointer is an optional pointer that points to the buffer that stores the source address after the overlap operation is completed.
Lpfromlen: In/out type parameter, a pointer pointing to the buffer size specified by lpfrom. this parameter is used only when the lpfrom parameter is specified.
Lpoverlapped: Pointer to the wsaoverlapped struct, which is ignored for non-overlapping sockets.
Lpcompletionroutine: A pointer to the completion routine called when the operation is completed. It is ignored for non-overlapping sockets.
<5> int wsasendto (socket S, lpwsabuf lpbuffers, dworddwbuffercount, lpdword blocks, DWORD dwflags, sockaddr * lpto, intlen, lpwsaoverlapped lpoverlapped, callback)
The parameters of this function correspond to those of wsarecvfrom.
Example program:
The following is a simple online chat program. let's first talk about its process:
1. Load the socket Library
2. initialize and bind the socket, which includes the definition of custom messages.
3. The custom message response function is complete.
4. The message sending function is complete.
The core code is as follows:
// Socket lib ready: initinstance () {// load the socket library word wversionrequested; wsadata; interr; wversionrequested = makeword (2, 2); err = wsastartup (wversionrequested, & wsadata); If (Err! = 0) {returnfalse;} If (lobyte (wsadata. wversion )! = 2 | hibyte (wsadata. wversion )! = 2) {wsacleanup (); returnfalse ;}//......}
// Create and initialize the socket boolcmfcachatdlg: initsocket (void) {m_socket = wsasocket (af_inet, sock_dgram, 0, null, 0, empty); If (invalid_socket = m_socket) {MessageBox (text ("create socket failed"); returnfalse;} sockaddr_in addrsock; addrsock. sin_family = af_inet; addrsock. sin_port = htons (6000); addrsock. sin_addr.s_un.s_addr = htonl (inaddr_any); interror = BIND (m_socket, (sockaddr *) & addrsock, sizeof (sockaddr); If (socket_error = Error) {MessageBox (text ("bind socket failed"); returnfalse;} error = wsaasyncselect (m_socket, m_hwnd, um_sock, fd_read); If (socket_error = Error) {MessageBox (text ("register network event failed"); returnfalse;} returntrue ;}
// Receive message response function fx_msg lresultcmfcachatdlg: onsock (wparam, lparam) {Switch (loword (lparam) {casefd_read: wsabuf; wsabuf. buf = new char [200]; wsabuf. len = 200; DWORD dwread; DWORD dwflag = 0; sockaddr_in addrfrom; intlen = sizeof (sockaddr); cstring STR; cstring strtemp; If (socket_error = wsarecvfrom (m_socket, & wsabuf, 1, & dwread, & dwflag, (sockaddr *) & addrfrom, & Len, null, null) {MessageBox (text ("receive datafailed"); Delete [] wsabuf. buf; wsabuf. buf = NULL; return 0;} Str. format (text ("% s say: % s"), inet_ntoa (addrfrom. sin_addr), wsabuf. buf); STR + = text ("\ r \ n"); getdlgitemtext (idc_edit_recv, strtemp); strtemp + = STR; setdlgitemtext (idc_edit_recv, strtemp); Delete [] wsabuf. buf; break;} return0 ;}
// Send the message void cmfcachatdlg: onbnclickedbtnsend () {// todo: add the control notification handler code DWORD dwip; cstring strsend; wsabuf; DWORD dwsend; intlen; sockaddr_in addrto; (cipaddressctrl *) getdlgitem (idc_ipaddress1)-> getaddress (dwip); addrto. sin_addr.s_un.s_addr = htonl (dwip); addrto. sin_family = af_inet; addrto. sin_port = htons (6000); getdlgitemtext (idc_edit_send, strsend); Len = strsend. getlength (); wsabuf. buf = strsend. getbuffer (LEN); wsabuf. len = Len + 1; if (socket_error = wsasendto (m_socket, & wsabuf, 1, & dwsend, 0, (sockaddr *) & addrto, sizeof (sockaddr), null, null) {MessageBox (text ("Send message failed"); return;} setdlgitemtext (idc_edit_send, text (""));}
Program running result
Message-based asynchronous socket