WIN网络编程-网络扩展函数

 1、GetAcceptExSockaddrs粘贴从AcceptEx函数取得的数据,将本地和远程地址传递到sockaddr结构,专门为AcceptEx函数准备的。返回AcceptEx接收的第一块数据中的本地和远程用户机器地址。
GetAcceptExSockaddrs Function

The GetAcceptExSockaddrs function parses the dataobtained from a call to the AcceptExfunction and passes the local and remote addresses to a sockaddrstructure.

Note  Thisfunction is a Microsoft-specific extension to the Windows Socketsspecification.

Syntax
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);
Parameters
lpOutputBuffer

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.

dwReceiveDataLength

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.

dwLocalAddressLength

Number of bytes reserved for the local address information. Mustbe equal to the dwLocalAddressLength parameter that waspassed to the AcceptExfunction.

dwRemoteAddressLength

Number of bytes reserved for the remote address information.This value must be equal to the dwRemoteAddressLengthparameter that was passed to the AcceptEx function.

LocalSockaddr

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.

LocalSockaddrLength

Size of the local address, in bytes. This parameter must bespecified.

RemoteSockaddr

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.

RemoteSockaddrLength

Size of the local address, in bytes. This parameter must bespecified.

Return Value

This function does not return a value.

Remarks

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.

Note  Thefunction 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.

 2、TransmitFile通过已经连接的SOCKET句柄传输文件,使用操作系统的缓冲管理器来接收数据并提供高质量的文件传输。
TransmitFile Function

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
);

Parameters
hSocket

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.

hFile

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.

nNumberOfBytesToWrite

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.

nNumberOfBytesPerSend

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.

lpOverlapped

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.

lpTransmitBuffers

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.

dwFlags

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:

TF_DISCONNECT

Start a transport-level disconnect after all the file data hasbeen queued for transmission.

TF_REUSE_SOCKET

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.

Note  Thesocket 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.

TF_USE_DEFAULT_WORKER

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

TF_USE_SYSTEM_THREAD

Directs the Windows Sockets service provider to use systemthreads to process long TransmitFile requests.

TF_USE_KERNEL_APC

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).

TF_WRITE_BEHIND

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.

Note  Ifthe file being sent is not in the file system cache, the requestpends.

Return Value

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.

Return codeDescription

WSAECONNABORTED

The virtual circuit was terminated due to a time-out or otherfailure.

WSAECONNRESET

For a stream socket, the virtual circuit was reset by the remoteside. The application should close the socket as it is no longerusable.

WSAEFAULT

The lpTransmitBuffers or lpOverlapped parameter isnot totally contained in a valid part of the user addressspace.

WSAEINVAL

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.

WSAENETDOWN

The network subsystem has failed.

WSAENETRESET

For a stream socket, the connection has been broken due tokeep-alive activity detecting a failure while the operation was inprogress.

WSAENOBUFS

The Windows Sockets provider reports a buffer deadlock.

WSAENOTCONN

The socket is not connected.

WSAENOTSOCK

The descriptor is not a socket.

WSAESHUTDOWN

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.

WSANOTINITIALISED

A successful WSAStartupcall must occur before using this function.

WSA_IO_PENDING

An overlapped operation was successfully initiated andcompletion will be indicated at a later time.

WSA_OPERATION_ABORTED

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.

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. For moreinformation, see ExitThread.

Remarks

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.

Note  Thefunction 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.

Note  TransmitFileis 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.

  • All pending receive data sent by remote side (received prior toa FIN from the remote side) on the TCP socket has been read.
  • The remote side has closed the connection (completed thegraceful TCP connection closure). 
3、既可以发送文件又可以发送内存缓冲区中的数据-TransmitPackets函数
TransmitPackets Function

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.

Note  Thisfunction is a Microsoft-specific extension to the Windows Socketsspecification.

Syntax
BOOL PASCAL TransmitPackets(    SOCKET hSocket,
//已经建立连接的SOCKET句柄,并不要求是面向连接的SOCKET LPTRANSMIT_PACKETS_ELEMENT lpPacketArray, DWORD nElementCount, DWORD nSendSize, LPOVERLAPPED lpOverlapped, DWORD dwFlags);
Parameters
hSocket

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.

lpPacketArray

An array of type TRANSMIT_PACKETS_ELEMENT,describing the data to be transmitted.

nElementCount

The number of elements in lpPacketArray.

nSendSize

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.

lpOverlapped

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.

dwFlags

A set of flags used to customize processing of theTransmitPackets function. The following table outlines theuse of the dwFlags parameter.

ValueMeaning

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.

Note  Thesocket 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/
     Parameters/TransmitWorker

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.

Return Value

Success returns TRUE, failure returns FALSE. Use the WSAGetLastErrorfunction to retrieve extended error information.

Remarks

The TransmitPackets function is optimized according tothe operating system on which it is used:

  • On Windows server editions, the TransmitPackets functionis optimized for high performance.
  • On Windows client editions, the TransmitPackets functionis optimized for minimum memory and resource utilization.

Note  Thefunction 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 WindowsServer 2003.

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.

Note  There is adifference between kernel and user-mode APCs:

  • Kernel APCs launch when a thread is in a wait state.
  • User-mode APCs launch when a thread is in an alertable waitstate.
4、为指定的套接字建立连接,连接建立之后也可以发送数据(称为连接数据)ConnectEx函数,允许重叠的连接调用。
The ConnectEx function establishes a connection to a specifiedsocket, and optionally sends data once the connection isestablished. The ConnectEx function is only supported onconnection-oriented sockets.

Note  Thisfunction is a Microsoft-specific extension to the Windows Socketsspecification.

Syntax
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);
Parameters
s

A descriptor that identifies an unconnected, previously boundsocket. See Remarks for more information.

name

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.

namelen

The length, in bytes, of the sockaddr structure pointedto by the name parameter.

lpSendBuffer

A pointer to the buffer to be transferred after a connection isestablished. This parameter is optional.

Note  Thisparameter 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.

dwSendDataLength

The length, in bytes, of data pointed to by thelpSendBuffer parameter. This parameter is ignored when thelpSendBuffer parameter is NULL.

lpdwBytesSent

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.

lpOverlapped

An OVERLAPPEDstructure used to process the request. The lpOverlappedparameter must be specified, and cannot be NULL.

Return Value

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.

Error codeDescription

WSANOTINITIALISED

A successful WSAStartupfunction call must occur before using ConnectEx.

WSAENETDOWN

The network subsystem has failed.

WSAEADDRINUSE

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.

WSAEALREADY

A nonblocking connect,WSAConnect,or ConnectEx function call is in progress on the specifiedsocket.

WSAEADDRNOTAVAIL

The remote address is not a valid address, such as ADDR_ANY (theConnectEx function is only supported for connection-orientedsockets).

WSAEAFNOSUPPORT

Addresses in the specified family cannot be used with thissocket.

WSAECONNREFUSED

The attempt to connect was rejected.

WSAEFAULT

The name, lpSendBuffer, or lpOverlappedparameter is not a valid part of the user address space, ornamelen is too small.

WSAEINVAL

The parameter s is an unbound or a listening socket.

WSAEISCONN

The socket is already connected.

WSAENETUNREACH

The network cannot be reached from this host at this time.

WSAEHOSTUNREACH

A socket operation was attempted to an unreachable host.

WSAENOBUFS

No buffer space is available; the socket cannot beconnected.

WSAENOTSOCK

The descriptor is not a socket.

WSAETIMEDOUT

The attempt to connect timed out without establishing aconnection.

Remarks

The ConnectEx function combines several socket functionsinto a single API/kernel transition. The following operations areperformed when a call to the ConnectEx function completessuccessfully:

  • A new connection is established.
  • An optional block of data is sent after the connection isestablished.

For applications targeted to Windows Vista 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:

Copy Code
 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:

Copy Code
 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);}
5、关闭SOCKET上的连接,允许重用SOCKET句柄-disconnectex
 DisconnectEx  
  The   DisconnectEx  function   closes  a   connection  on   a  socket,   and   allows  the   socket  handle   to   be  reused.  
   
  BOOL   DisconnectEx( 
      SOCKET  hSocket,  
     LPOVERLAPPED   lpOverlapped, 
      DWORD  dwFlags,  
      DWORD  reserved  
  );  
   
  Parameters  
  hSocket   
  [in]   Handle  to   a  connected,   connection-oriented  socket.   
  lpOverlapped   
  [in]   Pointer  to   an  OVERLAPPED   structure.   If  the   socket  handle   has   been  opened   as  overlapped,   specifying   this  parameter   results  in   overlapped  (asynchronous)   I/O  operation.   Socket  handles   are  overlapped   by  default.   
  dwFlags   
  [in]   Specifies  a   flag  that   customizes   processing  of   the  function   call.   The  dwFlags   parameter  has   one  optional   flag.Flag   Meaning   
  TF_REUSE_SOCKET   Prepares  the   socket  handle   to   be  reused.   When  the   DisconnectEx  request   completes,  the   socket  handle   can   be  passed   to  the   AcceptEx   or  ConnectEx   function. 
  Note     The  socket   level  disconnect   is  subject   to  the   behavior   of  the   underlying  transport.   For  example,   a  TCP   socket   may  be   subject  to   the   TCP  TIME_WAIT   state,   causing  the   DisconnectEx  call   to   be  delayed.  
     
   
  reserved   
  [in]   Reserved.  Must   be  zero.   If   nonzero,  WSAEINVAL   is  returned.   
  Return   Values 
  Success   returns  TRUE,   failure  returns   FALSE.  Use   the  WSAGetLastError   function   to  get   extended  error   information.  If   a   call  to   the  WSAGetLastError   function  returns   ERROR_IO_PENDING,   the  operation   initiated  successfully   and  is   in  progress.  
  Remarks  
  The   DisconnectEx  function   does  not   support  datagram   sockets.  Therefore,   the  socket   specified  by   hSocket  must   be   connection-oriented,  such   as   a  SOCK_STREAM,   SOCK_SEQPACKET,  or   SOCK_RDM  socket.  
   
  When   lpOverlapped  is   not  NULL,   overlapped   I/O  might   not  finish   before   DisconnectEx  returns,   resulting  in   the  DisconnectEx   function  returning   FALSE   and  a   call   to  the   WSAGetLastError  function   returning  ERROR_IO_PENDING.   This  design   enables  the   caller  to   continue   processing  while   the  disconnect   operation  completes.   Upon   completion  of   the  request,   Windows   sets  either   the  event   specified   by  the   hEvent  member   of   the  OVERLAPPED   structure,  or   the  socket   specified   by  hSocket,   to  the   signaled  state.  
   
  Note      All   I/O  initiated   by   a  given   thread  is   cancelled  when   that  thread   exits.   For  overlapped   sockets,  pending   asynchronous  operations   can  fail   if  the   thread   is  closed   before  the   operations  complete.   See  ExitThread   for  more   information. 
   
  Note     The  function   pointer  for   the  DisconnectEx   function   is  obtained   at  run   time  by   making   a  call   to  the   WSAIoctl   function  with   the  SIO_GET_EXTENSION_FUNCTION_POINTER   opcode  specified.  
   
  Note      Windows   TCP  reverts   to  a   TIME_WAIT   state  subsequent   to  the   closing  of   a  connection.   While   in  the   TIME_WAIT  state,   a  socket   pair   cannot  be   re-used.  The   TIME_WAIT  period   is  configurable   by   the  TcpTimedWaitDelay   registry  setting.  
   
  Requirements  
  Client:   Requires  Windows   XP. 
  Server:   Requires  Windows   Server  2003.  
  Header:   Declared  in  Mswsock.h.  
///////////////////////////////////////////////////////////////// // 初始化Socket bool CIOCPModel::_InitializeListenSocket() { // AcceptEx 和 GetAcceptExSockaddrs 的GUID,用于导出函数指针 GUID GuidAcceptEx = WSAID_ACCEPTEX; GUID GuidGetAcceptExSockAddrs = WSAID_GETACCEPTEXSOCKADDRS; // 服务器地址信息,用于绑定Socket struct sockaddr_in ServerAddress; // 生成用于监听的Socket的信息 m_pListenContext = new PER_SOCKET_CONTEXT; // 需要使用重叠IO,必须得使用WSASocket来建立Socket,才可以支持重叠IO操作 m_pListenContext->m_Socket = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED); if (INVALID_SOCKET == m_pListenContext->m_Socket) { this->_ShowMessage("初始化Socket失败,错误代码: %d.\n", WSAGetLastError()); return false; } else { TRACE("WSASocket() 完成.\n"); } // 将Listen Socket绑定至完成端口中 if( NULL== CreateIoCompletionPort( (HANDLE)m_pListenContext->m_Socket, m_hIOCompletionPort,(DWORD)m_pListenContext, 0)) { this->_ShowMessage("绑定 Listen Socket至完成端口失败!错误代码: %d/n", WSAGetLastError()); RELEASE_SOCKET( m_pListenContext->m_Socket ); return false; } else { TRACE("Listen Socket绑定完成端口 完成.\n"); } // 填充地址信息 ZeroMemory((char *)&ServerAddress, sizeof(ServerAddress)); ServerAddress.sin_family = AF_INET; // 这里可以绑定任何可用的IP地址,或者绑定一个指定的IP地址 //ServerAddress.sin_addr.s_addr = htonl(INADDR_ANY); ServerAddress.sin_addr.s_addr = inet_addr(m_strIP.GetString()); ServerAddress.sin_port = htons(m_nPort); // 绑定地址和端口 if (SOCKET_ERROR == bind(m_pListenContext->m_Socket, (struct sockaddr *) &ServerAddress, sizeof(ServerAddress))) { this->_ShowMessage("bind()函数执行错误.\n"); return false; } else { TRACE("bind() 完成.\n"); } // 开始进行监听 if (SOCKET_ERROR == listen(m_pListenContext->m_Socket,SOMAXCONN)) { this->_ShowMessage("Listen()函数执行出现错误.\n"); return false; } else { TRACE("Listen() 完成.\n"); } // 使用AcceptEx函数,因为这个是属于WinSock2规范之外的微软另外提供的扩展函数 // 所以需要额外获取一下函数的指针, // 获取AcceptEx函数指针 DWORD dwBytes = 0; if(SOCKET_ERROR == WSAIoctl
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值