`
deepfuture
  • 浏览: 4335233 次
  • 性别: Icon_minigender_1
  • 来自: 湛江
博客专栏
073ec2a9-85b7-3ebf-a3bb-c6361e6c6f64
SQLite源码剖析
浏览量:79439
1591c4b8-62f1-3d3e-9551-25c77465da96
WIN32汇编语言学习应用...
浏览量:68419
F5390db6-59dd-338f-ba18-4e93943ff06a
神奇的perl
浏览量:101543
Dac44363-8a80-3836-99aa-f7b7780fa6e2
lucene等搜索引擎解析...
浏览量:281288
Ec49a563-4109-3c69-9c83-8f6d068ba113
深入lucene3.5源码...
浏览量:14620
9b99bfc2-19c2-3346-9100-7f8879c731ce
VB.NET并行与分布式编...
浏览量:65620
B1db2af3-06b3-35bb-ac08-59ff2d1324b4
silverlight 5...
浏览量:31339
4a56b548-ab3d-35af-a984-e0781d142c23
算法下午茶系列
浏览量:45234
社区版块
存档分类
最新评论

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.

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

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.

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.

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.

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.

NoteIfthe 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 code Description

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.

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.

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.

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.

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

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

Value Meaning

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

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:

  • 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函数,允许重叠的连接调用。
TheConnectEx function establishes a connection to a specifiedsocket, and optionally sends data once the connection isestablished. The ConnectEx function is only supported onconnection-oriented sockets.

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

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.

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 code Description

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 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);}
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.
分享到:
评论

相关推荐

    网络编程实用教程(第三版).zip

    3.2.6 WSAAsyncGetXByY类型的扩展函数 79 3.3 网络应用程序的运行环境 82 习题 84 第4章 MFC编程 85 4.1 MFC概述 85 4.1.1 MFC是一个编程框架 85 4.1.2 典型的MDI应用程序的构成 87 4.2 MFC和Win32 ...

    《Windows网络编程技术》高清PDF版+随书源码

    高级网络编程6.1 简单MFC网络编程6.1.1 网络聊天应用实例6.1.2 MFC基本...编程模型6.3.3 HTTP网络应用实例算法及实现附录1 网络、应用程序开发说明附1.1 网络体系结构的概念附1.2 可执行文件的PE格式附1.3 VC++的项目...

    mongodb-win32-x86_64-2008plus-ssl-v3.4-latest-signed.msi

    你可以通过本地或者网络创建数据镜像,这使得MongoDB有更强的扩展性。 如果负载的增加(需要更多的存储空间和更强的处理能力) ,它可以分布在计算机网络中的其他节点上这就是所谓的分片。 Mongo支持丰富的查询...

    WINDOWS网络编程技术.pdf

    高级网络编程6.1 简单MFC网络编程6.1.1 网络聊天应用实例6.1.2 MFC基本...编程模型6.3.3 HTTP网络应用实例算法及实现附录1 网络、应用程序开发说明附1.1 网络体系结构的概念附1.2 可执行文件的PE格式附1.3 VC++的项目...

    window32 API大全 win32编程

    Win32 API作为 Microsoft 32位平台(包括:Windows 9x,Windows NT3.1/4.0/5.0,WindowsCE)的应用程序编程接口,它是构筑所有32位Windows平台的基石,所有在Windows平台上运行的应用程序都可以调用这些函数。...

    Windows网络编程

    1084.1.10 其他特征 1084.2 支持的协议 1084.2.1 支持的Win32网络协议 1094.2.2 Windows CE网络协议 1104.3 网际协议(IP) 1104.3.1 IP主要特征 1104.3.2 IP数据报格式 1114.3.3 IP服务定义和原语 1164.3.4...

    XJRegLib 注册表扩展函数库 1.0 B9

    XJRegLib 是 Win9X/ME 下的注册表扩展功能模块。使用它,您将会发现玩转注册表竟如此简单!创建主键、各种类型的键值;复制主键、键值;查找、删除主键、键值;轻松遍历注册表等等操作都易如反掌!大多数行为都可用...

    windows网络编程(PDF)

    射36414.2 传输服务提供者36414.2.1 WSPStartup36514.2.2 参数36614.2.3 实例计数36914.2.4 套接字句柄36914.2.5 Winsock I/O模型支持37114.2.6 扩展函数38014.2.7 传输服务提供者的安装38114.3 命名空间服务提供者...

    windows网络编程

    射36414.2 传输服务提供者36414.2.1 WSPStartup36514.2.2 参数36614.2.3 实例计数36914.2.4 套接字句柄36914.2.5 Winsock I/O模型支持37114.2.6 扩展函数38014.2.7 传输服务提供者的安装38114.3 命名空间服务提供者...

    maxima-clisp-sbcl-5.44.0-win64.exe

    可以以编程方式访问和扩展,因为可以从中调用基础Lisp。 完整的编程语言,具有类似于ALGOL的语法但具有类似Lisp的语义。 任意精度整数。 大小的合理数量仅受计算机内存限制。 任意大的浮点数(“ bfloats”)。

    Python 核心编程 第二版

    第2部分则提供了各种高级主题来展示可以使用Python做些什么,包括正则表达式、网络编程、网络客户端编程、多线程编程、图形用户界面编程、 Web编程、数据库编程、扩展Python 和一些其他材料。  本书适合Python初学...

    《WINDOWS网络编程技术》

    37114.2.6 扩展函数 38014.2.7 传输服务提供者的安装 38114.3 命名空间服务提供者 38614.3.1 名字空间的安装 38614.3.2 名字空间的实施 38714.3.3 名字空间提供者示范 39214.4 Winsock SPI函数的调试追踪 39614.5 小...

    WINDOWS网络编程技术

    射36414.2 传输服务提供者36414.2.1 WSPStartup36514.2.2 参数36614.2.3 实例计数36914.2.4 套接字句柄36914.2.5 Winsock I/O模型支持37114.2.6 扩展函数38014.2.7 传输服务提供者的安装38114.3 命名空间服务提供者...

Global site tag (gtag.js) - Google Analytics