The WSASend function sends data on a connected socket.
Syntax
int WSASend(
__in SOCKET s,
__in LPWSABUF lpBuffers,
__in DWORD dwBufferCount,
__out LPDWORD lpNumberOfBytesSent,
__in DWORD dwFlags,
__in LPWSAOVERLAPPED lpOverlapped,
__in LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);
Parameters
-
s [in]
-
A descriptor that identifies a connected socket.
-
lpBuffers [in]
-
A pointer to an array of WSABUF structures. Each WSABUF structure contains a pointer to a buffer and the length, in bytes, of the buffer. For a Winsock application, once the WSASend function is called, the system owns these buffers and the application may not access them. This array must remain valid for the duration of the send operation.
一個指向WSABUF結構數組的指針。每個WSABUF結構包含緩沖區的指針和緩沖區的大小。
-
dwBufferCount [in]
-
The number of WSABUF structures in the lpBuffers array.
lpBuffers數組中WSABUF結構的大小。
lpNumberOfBytesSent [out]
-
A pointer to the number, in bytes, sent by this call if the I/O operation completes immediately. If the lpOverlapped parameter is non-NULL, this parameter is optional and can be set to NULL.
如果發送操作立即完成,則為一個指向所發送數據字節數的指針。
-
dwFlags [in]
-
The flags used to modify the behavior of the WSASend function call. For more information, see Using dwFlags in the Remarks section.
標志位。
-
lpOverlapped [in]
-
A pointer to a WSAOVERLAPPED structure. This parameter is ignored for nonoverlapped sockets.
指向WSAOVERLAPPED結構的指針(對于非重疊套接口則忽略)。
-
lpCompletionRoutine [in]
-
A pointer to the completion routine called when the send operation has been completed. This parameter is ignored for nonoverlapped sockets.
一個指向發送操作完成后調用的完成例程的指針。(對于非重疊套接口則忽略)。
Return Value
返回值
If no error occurs and the send operation has completed immediately, WSASend returns zero. In this case, the completion routine will have already been scheduled to be called once the calling thread is in the alertable state. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError. The error code WSA_IO_PENDING indicates that the overlapped operation has been successfully initiated and that completion will be indicated at a later time. Any other error code indicates that the overlapped operation was not successfully initiated and no completion indication will occur.
若無錯誤發生且發送操作立即完成,則WSASend()函數返回所發送的字節數。(注意該數目可能小于len參數所指定的值)。如果連接結束,則返回0。請注意在這種情況下完成指示(啟動指定的完成例程或設置一個事件對象)將早已發生。否則的話,將返回SOCKET_ERROR錯誤,應用程序可通過WSAGetLastError()來獲取相應的錯誤代碼。錯誤代碼WSA_IO_PENDING表示重疊操作成功啟動,過后將有完成指示。任何其他的錯誤表示重疊操作未能成功地啟動,以后也不會有完成指示。
如果設置了MSG_INTERRUPT標志,則返回值的含義變化。零表示成功,具體含義同上。否則的話,返回值直接包含如下所示的錯誤代碼。由于中斷環境中無法調用WSAGetLastError(),故是必需的。請注意僅適用于Win16環境,僅適用于PROTOCOL_INFO結構中設置了XP1_INTERRUPT位的協議。
?
Error code
|
Meaning |
WSAECONNABORTED
|
The virtual circuit was terminated due to a time-out or other failure. 由于超時或其他錯誤導致虛電路中止
|
WSAECONNRESET
|
For a stream socket, the virtual circuit was reset by the remote side. The application should close the socket as it is no longer usable. For a UDP datagram socket, this error would indicate that a previous send operation resulted in an ICMP "Port Unreachable" message. ?虛電路被遠端復位。
|
WSAEFAULT
|
The lpBuffers, lpNumberOfBytesSent, lpOverlapped, lpCompletionRoutine parameter is not totally contained in a valid part of the user address space. lpBuffer參數并不是用戶地址空間的一個有效部分。
|
WSAEINTR
|
A blocking Windows Socket 1.1 call was canceled through WSACancelBlockingCall. 通過WSACancelBlockingCall()函數取消(阻塞)調用。
|
WSAEINPROGRESS
|
A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function. 一個阻塞的WinSock調用正在進行中,或者服務提供者仍在處理一個回調函數
|
WSAEINVAL
|
The socket has not been bound with bind or the socket is not created with the overlapped flag. 套接口未用bind()捆綁,或者套接口未用重疊標志位創建。
|
WSAEMSGSIZE
|
The socket is message oriented, and the message is larger than the maximum supported by the underlying transport. 套接口是面向消息的,但是消息大于底層傳送的最大值。
|
WSAENETDOWN
|
The network subsystem has failed. 網絡子系統失效。
|
WSAENETRESET
|
For a stream socket, the connection has been broken due to keep-alive activity detecting a failure while the operation was in progress. For a datagram socket, this error indicates that the time to live has expired. 由于遠端復位造成連接的中止。
|
WSAENOBUFS
|
The Windows Sockets provider reports a buffer deadlock. WinSock提供者報告一個緩沖區死鎖。
|
WSAENOTCONN
|
The socket is not connected. 套接口未連接。
|
WSAENOTSOCK
|
The descriptor is not a socket. 描述字不是一個套接口。
|
WSAEOPNOTSUPP
|
MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the communication domain associated with this socket, MSG_PARTIAL is not supported, or the socket is unidirectional and supports only receive operations. 設置了MSG_OOB,但是該套接口不是諸如SOCK_STREAM流類型的,與套接口相關的通訊域不支持帶外數據,或者套接口是單向的,只支持接收操作。
|
WSAESHUTDOWN
|
The socket has been shut down; it is not possible to WSASend on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH. 套接口已經關閉;一個套接口以SD_SEND或SD _BOTH的how參數shutdown()后,無法進行WSASend()調用。
|
WSAEWOULDBLOCK
|
Windows?NT:??
Overlapped sockets: There are too many outstanding overlapped I/O requests. Nonoverlapped sockets: The socket is marked as nonblocking and the send operation cannot be completed immediately. 太多的重疊輸入/輸出操作。
|
WSANOTINITIALISED
|
A successful WSAStartup call must occur before using this function. 在調用本API之前應成功調用WSAStartup()。
|
WSA_IO_PENDING
|
An overlapped operation was successfully initiated and completion will be indicated at a later time. 成功啟動重疊操作,過后將有完成指示。
|
WSA_OPERATION_ABORTED
|
The overlapped operation has been canceled due to the closure of the socket, the execution of the "SIO_FLUSH" command in WSAIoctl, or the thread that initiated the overlapped request exited before the operation completed. For more information, see the Remarks section.
|
Remarks
The WSASend function provides functionality over and above the standard send function in two important areas:
- It can be used in conjunction with overlapped sockets to perform overlapped send operations.
- It allows multiple send buffers to be specified making it applicable to the scatter/gather type of I/O.
The WSASend function is used to write outgoing data from one or more buffers on a connection-oriented socket specified by s. It can also be used, however, on connectionless sockets that have a stipulated default peer address established through the connect or WSAConnect function.
A socket created by the socket function will have the overlapped attribute as the default. A socket created by the WSASocket function with the dwFlags parameter passed to WSASocket with the WSA_FLAG_OVERLAPPED bit set will have the overlapped attribute. For sockets with the overlapped attribute, WSASend uses overlapped I/O unless both the lpOverlapped and lpCompletionRoutine parameters are NULL. In that case, the socket is treated as a non-overlapped socket. A completion indication will occur, invoking the completion of a routine or setting of an event object, when the buffer(s) have been consumed by the transport. If the operation does not complete immediately, the final completion status is retrieved through the completion routine or WSAGetOverlappedResult.
If both lpOverlapped and lpCompletionRoutine are NULL, the socket in this function will be treated as a non-overlapped socket.
For non-overlapped sockets, the last two parameters (lpOverlapped, lpCompletionRoutine) are ignored and WSASend adopts the same blocking semantics as send. Data is copied from the buffer(s) into the transport's buffer. If the socket is non-blocking and stream-oriented, and there is not sufficient space in the transport's buffer, WSASend will return with only part of the application's buffers having been consumed. Given the same buffer situation and a blocking socket, WSASend will block until all of the application buffer contents have been consumed.
Note??The socket options SO_RCVTIMEO and SO_SNDTIMEO apply only to blocking sockets.
If this function is completed in an overlapped manner, it is the Winsock service provider's responsibility to capture the WSABUF structures before returning from this call. This enables applications to build stack-based WSABUF arrays pointed to by the lpBuffers parameter.
For message-oriented sockets, do not exceed the maximum message size of the underlying provider, which can be obtained by getting the value of socket option SO_MAX_MSG_SIZE. If the data is too long to pass atomically through the underlying protocol the error WSAEMSGSIZE is returned, and no data is transmitted.
Windows?Me/98/95:??The WSASend function does not support more than 16 buffers.
Note??The successful completion of a WSASend does not indicate that the data was successfully delivered.
Using dwFlags
The dwFlags parameter can be used to influence the behavior of the function invocation beyond the options specified for the associated socket. That is, the semantics of this function are determined by the socket options and the dwFlags parameter. The latter is constructed by using the bitwise OR operator with any of any of the values listed in the following table.
Value |
Meaning |
MSG_DONTROUTE |
Specifies that the data should not be subject to routing. A Windows Sockets service provider can choose to ignore this flag. |
MSG_OOB |
Send OOB data on a stream-style socket such as SOCK_STREAM only. |
MSG_PARTIAL |
Specifies that lpBuffers only contains a partial message. Be aware that the error code WSAEOPNOTSUPP will be returned by transports that do not support partial message transmissions. |
Overlapped Socket I/O
If an overlapped operation completes immediately, WSASend returns a value of zero and the lpNumberOfBytesSent parameter is updated with the number of bytes sent. If the overlapped operation is successfully initiated and will complete later, WSASend returns SOCKET_ERROR and indicates error code WSA_IO_PENDING. In this case, lpNumberOfBytesSent is not updated. When the overlapped operation completes the amount of data transferred is indicated either through the cbTransferred parameter in the completion routine (if specified), or through the lpcbTransfer parameter in WSAGetOverlappedResult.
Note??All I/O initiated by a given thread is canceled when that thread exits. For overlapped sockets, pending asynchronous operations can fail if the thread is closed before the operations complete. For more information, see ExitThread.
The WSASend function can be called from within the completion routine of a previous WSARecv, WSARecvFrom, WSASend, or WSASendTo function. This enables time-sensitive data transmissions to occur entirely within a preemptive context.
The lpOverlapped parameter must be valid for the duration of the overlapped operation. If multiple I/O operations are simultaneously outstanding, each must reference a separate WSAOVERLAPPED structure.
If the lpCompletionRoutine parameter is NULL, the hEvent parameter of lpOverlapped is signaled when the overlapped operation completes if it contains a valid event object handle. An application can use WSAWaitForMultipleEvents or WSAGetOverlappedResult to wait or poll on the event object.
If lpCompletionRoutine is not NULL, the hEvent parameter is ignored and can be used by the application to pass context information to the completion routine. A caller that passes a non-NULL?lpCompletionRoutine and later calls WSAGetOverlappedResult for the same overlapped I/O request may not set the fWait parameter for that invocation of WSAGetOverlappedResult to TRUE. In this case the usage of the hEvent parameter is undefined, and attempting to wait on the hEvent parameter would produce unpredictable results.
The completion routine follows the same rules as stipulated for Windows file I/O completion routines. The completion routine will not be invoked until the thread is in an alertable wait state such as can occur when the function WSAWaitForMultipleEvents with the fAlertable parameter set to TRUE is invoked.
The transport providers allow an application to invoke send and receive operations from within the context of the socket I/O completion routine, and guarantee that, for a given socket, I/O completion routines will not be nested. This permits time-sensitive data transmissions to occur entirely within a preemptive context.
The following C++ code example is a prototype of the completion routine.
void CALLBACK CompletionROUTINE(
IN DWORD dwError,
IN DWORD cbTransferred,
IN LPWSAOVERLAPPED lpOverlapped,
IN DWORD dwFlags
);
The CompletionRoutine function is a placeholder for an application-defined or library-defined function name. The dwError parameter specifies the completion status for the overlapped operation as indicated by lpOverlapped. cbTransferred specifies the number of bytes sent. Currently there are no flag values defined and dwFlags will be zero. This function does not return a value.
Returning from this function allows invocation of another pending completion routine for this socket. All waiting completion routines are called before the alertable thread's wait is satisfied with a return code of WSA_IO_COMPLETION. The completion routines can be called in any order, not necessarily in the same order the overlapped operations are completed. However, the posted buffers are guaranteed to be sent in the same order they are specified.
If you are using I/O completion ports, be aware that the order of calls made to WSASend is also the order in which the buffers are populated. WSASend should not be called on the same socket simultaneously from different threads, because it can result in an unpredictable buffer order.
Example Code
The following code example shows how to use the WSASend function in overlapped I/O mode.
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
#define DATA_BUFSIZE 4096
#define SEND_COUNT 10
int __cdecl main()
{
WSADATA wsd;
struct addrinfo *result = NULL;
struct addrinfo hints = { 0 };
WSAOVERLAPPED SendOverlapped = { 0 };
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET AcceptSocket = INVALID_SOCKET;
WSABUF DataBuf;
DWORD SendBytes;
DWORD Flags;
char buffer[DATA_BUFSIZE];
int err, rc, i;
// Load Winsock
rc = WSAStartup(MAKEWORD(2, 2), &wsd);
if (rc != 0) {
fprintf(stderr, "Unable to load Winsock: %d\n", rc);
return 1;
}
// Initialize the hints to obtain the
// wildcard bind address for IPv4
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
rc = getaddrinfo(NULL, "27015", &hints, &result);
if (rc != 0) {
fprintf(stderr, "getaddrinfo failed: %d\n", rc);
return 1;
}
ListenSocket = socket(result->ai_family,
result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
fprintf(stderr, "socket failed: %d\n", WSAGetLastError());
freeaddrinfo(result);
return 1;
}
rc = bind(ListenSocket, result->ai_addr, (int) result->ai_addrlen);
if (rc == SOCKET_ERROR) {
fprintf(stderr, "bind failed: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
return 1;
}
rc = listen(ListenSocket, 1);
if (rc == SOCKET_ERROR) {
fprintf(stderr, "listen failed: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
return 1;
}
// Accept an incoming connection request
AcceptSocket = accept(ListenSocket, NULL, NULL);
if (AcceptSocket == INVALID_SOCKET) {
fprintf(stderr, "accept failed: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
return 1;
}
printf("Client Accepted...\n");
// Create an event handle and setup an overlapped structure.
SendOverlapped.hEvent = WSACreateEvent();
if (SendOverlapped.hEvent == NULL) {
fprintf(stderr, "WSACreateEvent failed: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
closesocket(AcceptSocket);
return 1;
}
DataBuf.len = DATA_BUFSIZE;
DataBuf.buf = buffer;
for (i = 0; i < SEND_COUNT; i++) {
rc = WSASend(AcceptSocket, &DataBuf, 1,
&SendBytes, 0, &SendOverlapped, NULL);
if ((rc == SOCKET_ERROR) &&
(WSA_IO_PENDING != (err = WSAGetLastError()))) {
fprintf(stderr, "WSASend failed: %d\n", err);
break;
}
rc = WSAWaitForMultipleEvents(1, &SendOverlapped.hEvent, TRUE, INFINITE,
TRUE);
if (rc == WSA_WAIT_FAILED) {
fprintf(stderr, "WSAWaitForMultipleEvents failed: %d\n",
WSAGetLastError());
break;
}
rc = WSAGetOverlappedResult(AcceptSocket, &SendOverlapped, &SendBytes,
FALSE, &Flags);
if (rc == FALSE) {
fprintf(stderr, "WSASend operation failed: %d\n",
WSAGetLastError());
break;
}
printf("Wrote %d bytes\n", SendBytes);
WSAResetEvent(SendOverlapped.hEvent);
}
WSACloseEvent(SendOverlapped.hEvent);
closesocket(AcceptSocket);
closesocket(ListenSocket);
freeaddrinfo(result);
WSACleanup();
return 0;
}
Requirements
Minimum supported client |
Windows 2000 Professional |
Minimum supported server |
Windows 2000 Server |
Header |
Winsock2.h |
Library |
Ws2_32.lib |
DLL |
Ws2_32.dll |
See Also