The GetAcceptExSockaddrs function parses the dataobtained from a call to the AcceptExfunction and passes the local and remote addresses to a sockaddrstructure.
NoteThisfunction is a Microsoft-specific extension to the Windows Socketsspecification.
void GetAcceptExSockaddrs( __in PVOID lpOutputBuffer,
//指向传递给AcceptEx函数接收客户第一块数据的缓冲区。 __in DWORD dwReceiveDataLength, __in DWORD dwLocalAddressLength, __in DWORD dwRemoteAddressLength, __out LPSOCKADDR* LocalSockaddr, __out LPINT LocalSockaddrLength, __out LPSOCKADDR* RemoteSockaddr, __out LPINT RemoteSockaddrLength);
Pointer to a buffer that receives the first block of data senton a connection resulting from an AcceptExcall. Must be the same lpOutputBuffer parameter that waspassed to the AcceptEx function.
Number of bytes in the buffer used for receiving the first data.This value must be equal to the dwReceiveDataLengthparameter that was passed to the AcceptEx function.
Number of bytes reserved for the local address information. Mustbe equal to the dwLocalAddressLength parameter that waspassed to the AcceptExfunction.
Number of bytes reserved for the remote address information.This value must be equal to the dwRemoteAddressLengthparameter that was passed to the AcceptEx function.
Pointer to the sockaddr structure that receives the localaddress of the connection (the same information that would bereturned by the getsocknamefunction). This parameter must be specified.
Size of the local address, in bytes. This parameter must bespecified.
Pointer to the sockaddr structure that receives theremote address of the connection (the same information that wouldbe returned by the getpeernamefunction). This parameter must be specified.
Size of the local address, in bytes. This parameter must bespecified.
This function does not return a value.
The GetAcceptExSockaddrs function is used exclusivelywith the AcceptExfunction to parse the first data that the socket receives intolocal and remote addresses. You are required to use this functionbecause the AcceptEx function writes address information inan internal (TDI) format. The GetAcceptExSockaddrs routineis required to locate the sockaddr structures in thebuffer.
NoteThefunction pointer for the GetAcceptExSockaddrs function mustbe obtained at run time by making a call to the WSAIoctlfunction with the SIO_GET_EXTENSION_FUNCTION_POINTER opcodespecified. The input buffer passed to the WSAIoctl functionmust contain WSAID_GETACCEPTEXSOCKADDRS, a globally uniqueidentifier (GUID) whose value identifies theGetAcceptExSockaddrs extension function. On success, theoutput returned by the WSAIoctl function contains a pointerto the GetAcceptExSockaddrs function. TheWSAID_GETACCEPTEXSOCKADDRS GUID is defined in the Mswsock.hheader file.
The TransmitFile function transmits file data over aconnected socket handle. This function uses the operating system'scache manager to retrieve the file data, and provideshigh-performance file data transfer over sockets.
BOOL TransmitFile(
SOCKEThSocket,
HANDLEhFile,
DWORDnNumberOfBytesToWrite,
DWORDnNumberOfBytesPerSend,
LPOVERLAPPEDlpOverlapped,
LPTRANSMIT_FILE_BUFFERS lpTransmitBuffers,
//意为文件数据发送之前和之后要发送的数据。如果hFile为NULL,
//lpTransmitBuffers将被传输。
DWORDdwFlags
);
A handle to a connected socket. The TransmitFile functionwill transmit the file data over this socket. The socket specifiedby the hSocket parameter must be a connection-orientedsocket of type SOCK_STREAM, SOCK_SEQPACKET, or SOCK_RDM.
A handle to the open file that the TransmitFile functiontransmits. Since the operating system reads the file datasequentially, you can improve caching performance by opening thehandle with FILE_FLAG_SEQUENTIAL_SCAN.
The hFile parameter is optional. If the hFileparameter is NULL, only data in the header and/or the tail bufferis transmitted. Any additional action, such as socket disconnect orreuse, is performed as specified by the dwFlagsparameter.
The number of bytes in the file to transmit. TheTransmitFile function completes when it has sent thespecified number of bytes, or when an error occurs, whicheveroccurs first.
Set this parameter to zero in order to transmit the entirefile.
The size, in bytes, of each block of data sent in each sendoperation. This parameter is used by Windows' sockets layer todetermine the block size for send operations. To select the defaultsend size, set this parameter to zero.
The nNumberOfBytesPerSend parameter is useful forprotocols that have limitations on the size of individual sendrequests.
A pointer to an OVERLAPPEDstructure. If the socket handle has been opened as overlapped,specify this parameter in order to achieve an overlapped(asynchronous) I/O operation. By default, socket handles are openedas overlapped.
You can use the lpOverlapped parameter to specify a64-bit offset within the file at which to start the file datatransfer by setting the Offset and OffsetHigh memberof the OVERLAPPED structure. If lpOverlapped is aNULL pointer, the transmission of data always starts at the currentbyte offset in the file.
When the lpOverlapped is not NULL, the overlapped I/Omight not finish before TransmitFile returns. In that case,the TransmitFile function returns FALSE, and WSAGetLastErrorreturns ERROR_IO_PENDING or WSA_IO_PENDING.This enables the caller to continue processing while the filetransmission operation completes. Windows will set the eventspecified by the hEvent member of the OVERLAPPEDstructure, or the socket specified by hSocket, to thesignaled state upon completion of the data transmissionrequest.
A pointer to a TRANSMIT_FILE_BUFFERSdata structure that contains pointers to data to send before andafter the file data is sent. This parameter should be set to a NULLpointer if you want to transmit only the file data.
A set of flags used to modify the behavior of theTransmitFile function call. The dwFlags parameter cancontain a combination of the following options defined in theMswsock.h header file:
Start a transport-level disconnect after all the file data hasbeen queued for transmission.
Prepare the socket handle to be reused. This flag is valid onlyif TF_DISCONNECT is also specified.
When the TransmitFile request completes, the sockethandle can be passed to the function call previously used toestablish the connection, such as AcceptEx orConnectEx.Such reuse is mutually exclusive; for example, if theAcceptEx function was called for the socket, reuse isallowed only for subsequent calls to the AcceptEx function,and not allowed for a subsequent call to ConnectEx.
NoteThesocket level file transmit is subject to the behavior of theunderlying transport. For example, a TCP socket may be subject tothe TCP TIME_WAIT state, causing the TransmitFile call to bedelayed.
Directs the Windows Sockets service provider to use the system'sdefault thread to process long TransmitFile requests. Thesystem default thread can be adjusted using the following registryparameter as a REG_DWORD:
HKEY_LOCAL_MACHINE\CurrentControlSet\Services\AFD\
Parameters\TransmitWorker
Directs the Windows Sockets service provider to use systemthreads to process long TransmitFile requests.
Directs the driver to use kernel asynchronous procedure calls(APCs) instead of worker threads to process longTransmitFile requests. Long TransmitFile requests aredefined as requests that require more than a single read from thefile or a cache; the request therefore depends on the size of thefile and the specified length of the send packet.
Use of TF_USE_KERNEL_APC can deliver significant performancebenefits. It is possible (though unlikely), however, that thethread in which context TransmitFile is initiated is beingused for heavy computations; this situation may prevent APCs fromlaunching. Note that the Winsock kernel mode driver uses normalkernel APCs, which launch whenever a thread is in a wait state,which differs from user-mode APCs, which launch whenever a threadis in an alertable wait state initiated in user mode).
Complete the TransmitFile request immediately, withoutpending. If this flag is specified and TransmitFilesucceeds, then the data has been accepted by the system but notnecessarily acknowledged by the remote end. Do not use this settingwith the TF_DISCONNECT and TF_REUSE_SOCKET flags.
NoteIfthe file being sent is not in the file system cache, the requestpends.
If the TransmitFile function succeeds, the return valueis TRUE. Otherwise, the return value is FALSE. To get extendederror information, call WSAGetLastError. An error code ofWSA_IO_PENDING orERROR_IO_PENDING indicates that the overlapped operation has beensuccessfully initiated and that completion will be indicated at alater time. Any other error code indicates that the overlappedoperation was not successfully initiated and no completionindication will occur. Applications should handle eitherERROR_IO_PENDING or WSA_IO_PENDING inthis case.
The virtual circuit was terminated due to a time-out or otherfailure. |
|
For a stream socket, the virtual circuit was reset by the remoteside. The application should close the socket as it is no longerusable. |
|
The lpTransmitBuffers or lpOverlapped parameter isnot totally contained in a valid part of the user addressspace. |
|
One of the function parameters is invalid. This error isreturned if the hSocket parameter specified a socket of typeSOCK_DGRAM or SOCK_RAW. This error is returned if thedwFlags parameter has the TF_REUSE_SOCKET flag set, but theTF_DISCONNECT flag was not set. This error is also returned if theoffset specified in the OVERLAPPED structure pointed to bythe lpOverlapped is not within the file. |
|
The network subsystem has failed. |
|
For a stream socket, the connection has been broken due tokeep-alive activity detecting a failure while the operation was inprogress. |
|
The Windows Sockets provider reports a buffer deadlock. |
|
The socket is not connected. |
|
The descriptor is not a socket. |
|
The socket has been shut down; it is not possible to callTransmitFile on a socket after shutdownfunction has been called on the socket with the howparameter set to SD_SEND or SD_BOTH. |
|
A successful WSAStartupcall must occur before using this function. |
|
An overlapped operation was successfully initiated andcompletion will be indicated at a later time. |
|
The overlapped operation has been canceled due to the closure ofthe socket, the execution of the "SIO_FLUSH" command in WSAIoctl, orthe thread that initiated the overlapped request exited before theoperation completed. NoteAllI/O initiated by a given thread is canceled when that thread exits.For overlapped sockets, pending asynchronous operations can fail ifthe thread is closed before the operations complete. For moreinformation, see ExitThread. |
The TransmitFile function uses the operating system'scache manager to retrieve the file data, and providehigh-performance file data transfer over sockets.
The TransmitFile function only supportsconnection-oriented sockets of type SOCK_STREAM, SOCK_SEQPACKET,and SOCK_RDM. Sockets of type SOCK_DGRAM and SOCK_RAW are notsupported. The TransmitPacketsfunction can be used with sockets of type SOCK_DGRAM.
NoteThefunction pointer for the TransmitFile function must beobtained at run time by making a call to the WSAIoctlfunction with the SIO_GET_EXTENSION_FUNCTION_POINTER opcodespecified. The input buffer passed to the WSAIoctl functionmust contain WSAID_TRANSMITFILE, a globally unique identifier(GUID) whose value identifies the TransmitFile extensionfunction. On success, the output returned by the WSAIoctlfunction contains a pointer to the TransmitFile function.The WSAID_TRANSMITFILE GUID is defined in the Mswsock.hheader file.
NoteTransmitFileis not functional on transports that perform their own buffering.Transports with the TDI_SERVICE_INTERNAL_BUFFERING flag set, suchas ADSP, perform their own buffering. Because TransmitFileachieves its performance gains by sending data directly from thefile cache. Transports that run out of buffer space on a particularconnection are not handled by TransmitFile, and as a resultof running out of buffer space on the connection,TransmitFile returns STATUS_DEVICE_NOT_READY.
Workstation and client versions of Windows optimize theTransmitFile function for minimum memory and resourceutilization by limiting the number of concurrentTransmitFile operations allowed on the system to a maximumof two.
Server versions of Windows optimize the TransmitFilefunction for high performance. On server versions, there are nodefault limits placed on the number of concurrentTransmitFile operations allowed on the system. Expect betterperformance results when using TransmitFile on serverversions of Windows. On server versions of Windows, it is possibleto set a limit on the maximum number of concurrentTransmitFile operations by creating a registry entry andsetting a value for the following REG_DWORD:
HKEY_LOCAL_MACHINE\CurrentControlSet\Services\AFD\
Parameters\MaxActiveTransmitFileCount
If the TransmitFile function is called with TCP socket(protocol of IPPROTO_TCP) with both the TF_DISCONNECT andTF_REUSE_SOCKET flags specified, the call will not complete untilthe two following conditions are met.
The TransmitPackets function transmits in-memory data orfile data over a connected socket. The TransmitPacketsfunction uses the operating system cache manager to retrieve filedata, locking memory for the minimum time required to transmit andresulting in efficient, high-performance transmission.
NoteThisfunction is a Microsoft-specific extension to the Windows Socketsspecification.
BOOL PASCAL TransmitPackets( SOCKET hSocket, //已经建立连接的SOCKET句柄,并不要求是面向连接的SOCKET LPTRANSMIT_PACKETS_ELEMENT lpPacketArray, DWORD nElementCount, DWORD nSendSize, LPOVERLAPPED lpOverlapped, DWORD dwFlags);
A handle to the connected socket to be used in the transmission.Although the socket does not need to be a connection-orientedcircuit, the default destination/peer should have been establishedusing the connect,WSAConnect,accept,WSAAccept,AcceptEx, orWSAJoinLeaffunction.
An array of type TRANSMIT_PACKETS_ELEMENT,describing the data to be transmitted.
The number of elements in lpPacketArray.
The size, in bytes, of the data block used in the sendoperation. Set nSendSize to zero to let the sockets layerselect a default send size.
Setting nSendSize to 0xFFFFFFF enables the caller tocontrol the size and content of each send request, achievedby using the TP_ELEMENT_EOP flag in theTRANSMIT_PACKETS_ELEMENT array pointed to in thelpPacketArray parameter. This capability is useful formessage protocols that place limitations on the size of individualsend requests.
A pointer to an OVERLAPPEDstructure. If the socket handle specified in the hSocketparameter has been opened as overlapped, use this parameter toachieve asynchronous (overlapped) I/O operation. Socket handles areopened as overlapped by default.
A set of flags used to customize processing of theTransmitPackets function. The following table outlines theuse of the dwFlags parameter.
TF_DISCONNECT |
Starts a transport-level disconnect after all the file data hasbeen queued for transmission. Applies only to connection-orientedsockets. Specifying this flag for sockets that do not supportdisconnect semantics (such as datagram sockets) results in anerror. |
TF_REUSE_SOCKET |
Prepares the socket handle to be reused. When theTransmitPackets function completes, the socket handle can bepassed to the AcceptExfunction. Valid only when a connection-oriented socket andTF_DISCONNECT are specified. NoteThesocket level packet transmit is subject to the behavior of theunderlying transport. For example, a TCP socket may be subject tothe TCP TIME_WAIT state, causing the TransmitPackets call tobe delayed. |
TF_USE_DEFAULT_WORKER |
Directs Winsock to use the system's default thread to processlong TransmitPackets requests. Long TransmitPacketsrequests are defined as requests that require more than a singleread from the file or a cache; the long request definitiontherefore depends on the size of the file and the specified lengthof the send packet. The system default thread can be adjusted using the followingregistry parameter as a REG_DWORD: HKEY_LOCAL_MACHINE\CurrentControlSet\Services\AFD\ |
TF_USE_SYSTEM_THREAD |
Directs Winsock to use system threads to process longTransmitPackets requests. Long TransmitPacketsrequests are defined as requests that require more than a singleread from the file or a cache; the long request definitiontherefore depends on the size of the file and the specified lengthof the send packet. |
TF_USE_KERNEL_APC |
Directs Winsock to use kernel Asynchronous ProcedureCalls (APCs) instead of worker threads to process longTransmitPackets requests. Long TransmitPacketsrequests are defined as requests that require more than a singleread from the file or a cache; the long request definitiontherefore depends on the size of the file and the specified lengthof the send packet. See Remarks for more information. |
Success returns TRUE, failure returns FALSE. Use the WSAGetLastErrorfunction to retrieve extended error information.
The TransmitPackets function is optimized according tothe operating system on which it is used:
NoteThefunction pointer for the TransmitPackets function must beobtained at run time by making a call to the WSAIoctlfunction with the SIO_GET_EXTENSION_FUNCTION_POINTER opcodespecified. The input buffer passed to the WSAIoctl functionmust contain WSAID_TRANSMITPACKETS, a globally unique identifier(GUID) whose value identifies the TransmitPackets extensionfunction. On success, the output returned by the WSAIoctlfunction contains a pointer to the TransmitPackets function.The WSAID_TRANSMITPACKETS GUID is defined in the Mswsock.hheader file.
Expect better performance results when using theTransmitPackets function on WindowsServer2003.
When lpOverlapped is not NULL, overlapped I/O might notfinish before the TransmitPackets function returns. Whenthis occurs, the TransmitPackets function returns fails, anda call to the WSAGetLastErrorfunction returns ERROR_IO_PENDING, allowing the caller to continueprocessing while the transmission completes.
Note AllI/O initiated by a given thread is canceled when that thread exits.For overlapped sockets, pending asynchronous operations can fail ifthe thread is closed before the operations complete. See ExitThreadfor more information.
When the TransmitPackets function returns TRUE or returnsFALSE and WSAGetLastError returns ERROR_IO_PENDING, Windowssets the event specified by the hEvent member of the OVERLAPPEDstructure or the socket specified by hSocket to the signaledstate, and upon completion, delivers notification to any completionport associated with the socket. Use GetOverlappedResult,or WSAGetOverlappedResult,or GetQueuedCompletionStatusto retrieve final status and number of bytes transmitted.
TransmitPackets and Asynchronous Procedure Calls (APCs)
Use of the TF_USE_KERNEL_APC flag can deliver significantperformance benefits. If the thread initiating theTransmitPackets function call is being used for heavycomputations, it is possible, though unlikely, that APCs could beprevented from launching.
NoteThere is adifference between kernel and user-mode APCs:
NoteThisfunction is a Microsoft-specific extension to the Windows Socketsspecification.
BOOL PASCAL ConnectEx( __in SOCKET s,//一个未连接的、已经绑定的SOCKET句柄 __in const struct sockaddr* name, __in int namelen, __in_opt PVOID lpSendBuffer, __in DWORD dwSendDataLength, __out LPDWORD lpdwBytesSent, __in LPOVERLAPPED lpOverlapped);
A descriptor that identifies an unconnected, previously boundsocket. See Remarks for more information.
A pointer to a sockaddrstructure that specifies the address to which to connect. For IPv4,the sockaddr contains AF_INET for the address family, thedestination IPv4 address, and the destination port. For IPv6, thesockaddr structure contains AF_INET6 for the address family,the destination IPv6 address, the destination port, and may containadditional IPv6 flow and scope-id information.
The length, in bytes, of the sockaddr structure pointedto by the name parameter.
A pointer to the buffer to be transferred after a connection isestablished. This parameter is optional.
NoteThisparameter does not point to "connect data" that is sent as part ofconnection establishment. To send "connect data" using theConnectEx function, the setsockoptfunction must be called on the unconnected socket s with theSO_CONNDATA socket option to set a pointer to a buffer containingthe connect data, and then called with the SO_CONNDATALEN socketoption to set the length of the "connect data" in the buffer. Thenthe ConnectEx function can be called. As an alternative, theWSAConnectfunction can be used if connect data is to be sent as part ofconnection establishment.
The length, in bytes, of data pointed to by thelpSendBuffer parameter. This parameter is ignored when thelpSendBuffer parameter is NULL.
On successful return, this parameter points to a DWORDvalue that indicates the number of bytes that were sent after theconnection was established. The bytes sent are from the bufferpointed to by the lpSendBuffer parameter. This parameter isignored when the lpSendBuffer parameter is NULL.
An OVERLAPPEDstructure used to process the request. The lpOverlappedparameter must be specified, and cannot be NULL.
On success, the ConnectEx function returns TRUE. Onfailure, the function returns FALSE. Use the WSAGetLastErrorfunction to get extended error information. If a call to theWSAGetLastError function returns ERROR_IO_PENDING, theoperation initiated successfully and is in progress. Under suchcircumstances, the call may still fail when the overlappedoperation completes.
If the error code returned is WSAECONNREFUSED,WSAENETUNREACH, orWSAETIMEDOUT, theapplication can call ConnectEx, WSAConnect, or connectagain on the same socket.
A successful WSAStartupfunction call must occur before using ConnectEx. |
|
The network subsystem has failed. |
|
The local address of the socket is already in use, and thesocket was not marked to allow address reuse with SO_REUSEADDR.This error usually occurs during a bindoperation, but the error could be delayed until a ConnectExfunction call, if the bind function operates on an addressinvolving ADDR_ANY (a partially wild-carded address), and if aspecific address needs to be committed at the time of theConnectEx function call. |
|
A nonblocking connect,WSAConnect,or ConnectEx function call is in progress on the specifiedsocket. |
|
The remote address is not a valid address, such as ADDR_ANY (theConnectEx function is only supported for connection-orientedsockets). |
|
Addresses in the specified family cannot be used with thissocket. |
|
The attempt to connect was rejected. |
|
The name, lpSendBuffer, or lpOverlappedparameter is not a valid part of the user address space, ornamelen is too small. |
|
The parameter s is an unbound or a listening socket. |
|
The socket is already connected. |
|
The network cannot be reached from this host at this time. |
|
A socket operation was attempted to an unreachable host. |
|
No buffer space is available; the socket cannot beconnected. |
|
The descriptor is not a socket. |
|
The attempt to connect timed out without establishing aconnection. |
The ConnectEx function combines several socket functionsinto a single API/kernel transition. The following operations areperformed when a call to the ConnectEx function completessuccessfully:
For applications targeted to WindowsVista andlater, consider using the WSAConnectByListor WSAConnectByNamefunction which greatly simplify client application design.
The ConnectEx function can only be used withconnection-oriented sockets. The socket passed in the sparameter must be created with a socket type of SOCK_STREAM,SOCK_RDM, or SOCK_SEQPACKET.
The lpSendBuffer parameter points to a buffer of data tosend after the connection is established. ThedwSendDataLength parameter specifies the length in bytes ofthis data to send. An application can request to send a largebuffer of data using the ConnectEx in the same way that thesend andWSASendfunctions can be used. But developers are strongly advised againstsending a huge buffer in a single call using ConnectEx,because this operation uses a large amount of system memoryresources until the whole buffer has been sent.
If the ConnectEx function is successful, a connection wasestablished and all of the data pointed to by thelpSendBuffer parameter was sent to the address specified inthe sockaddr structure pointed to by the nameparameter.
If the TransmitFile function is called on apreviously connected socket with both TF_DISCONNECT andTF_REUSE_SOCKET flags, the specified socket is returned to a statein which it is not connected, but still bound. In such cases, thehandle of the socket can be passed to the ConnectEx functionin its s parameter, but the socket cannot be reused in anAcceptExfunction call. Similarly, the accepted socket reused using theTransmitFile function cannot be used in a call toConnectEx. Note that in the case of a reused socket,ConnectEx is subject to the behavior of the underlyingtransport. For example, a TCP socket may be subject to the TCPTIME_WAIT state, causing the ConnectEx call to bedelayed.
When the ConnectEx function returns, the socket sis in the default state for a connected socket. The socket sdoes not enable previously set properties or options untilSO_UPDATE_CONNECT_CONTEXT is set on the socket. Use thesetsockopt function to set the SO_UPDATE_CONNECT_CONTEXToption.
For example:
err = setsockopt( s, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0 );
The getsockoptfunction can be used with the SO_CONNECT_TIME socket option tocheck whether a connection has been established whileConnectEx is in progress. If a connection has beenestablished, the value returned in the optval parameterpassed to the getsockopt function is the number of secondsthe socket has been connected. If the socket is not connected, thereturned optval parameter contains 0xFFFFFFFF. Checking aconnection in this manner is necessary to determine whetherconnections have been established for a period of time withoutsending any data; in such cases, it is recommended that suchconnections be terminated.
For example:
int seconds;int bytes = sizeof(seconds);err = getsockopt( s, SOL_SOCKET, SO_CONNECT_TIME, (char *)&seconds, (PINT)&bytes );if ( err != NO_ERROR ) { printf( "getsockopt(SO_CONNECT_TIME) failed with error: %ld\n", WSAGetLastError() );}else { if (seconds == 0xFFFFFFFF) printf("Connection not established yet\n"); else printf("Connection has been established %ld seconds\n", seconds);}