send function

本文详细介绍了使用send函数将数据发送到已连接的套接字的方法,包括参数说明、返回值、错误码以及注意事项。通过一个示例代码展示了如何正确使用send函数实现数据发送。

The send function sends data on a connected socket.

Syntax

C++
int send(
  _In_  SOCKET s,
  _In_  const char *buf,
  _In_  int len,
  _In_  int flags
);

Parameters

s [in]

A descriptor identifying a connected socket.

buf [in]

A pointer to a buffer containing the data to be transmitted.

len [in]

The length, in bytes, of the data in buffer pointed to by the buf parameter.

flags [in]

A set of flags that specify the way in which the call is made. This parameter is constructed by using the bitwise OR operator with any of the following values.

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

Sends OOB data (stream-style socket such as SOCK_STREAM only.

 

Return value

If no error occurs, send returns the total number of bytes sent, which can be less than the number requested to be sent in the len parameter. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.

Error code Meaning
WSANOTINITIALISED

A successful WSAStartup call must occur before using this function.

WSAENETDOWN

The network subsystem has failed.

WSAEACCES

The requested address is a broadcast address, but the appropriate flag was not set. Call setsockopt with the SO_BROADCAST socket option to enable use of the broadcast address.

WSAEINTR

A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall.

WSAEINPROGRESS

A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.

WSAEFAULT

The buf parameter is not completely contained in a valid part of the user address space.

WSAENETRESET

The connection has been broken due to the keep-alive activity detecting a failure while the operation was in progress.

WSAENOBUFS

No buffer space is available.

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, or the socket is unidirectional and supports only receive operations.

WSAESHUTDOWN

The socket has been shut down; it is not possible to send on a socket aftershutdown has been invoked with how set to SD_SEND or SD_BOTH.

WSAEWOULDBLOCK

The socket is marked as nonblocking and the requested operation would block.

WSAEMSGSIZE

The socket is message oriented, and the message is larger than the maximum supported by the underlying transport.

WSAEHOSTUNREACH

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

WSAEINVAL

The socket has not been bound with bind, or an unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled.

WSAECONNABORTED

The virtual circuit was terminated due to a time-out or other failure. The application should close the socket as it is no longer usable.

WSAECONNRESET

The virtual circuit was reset by the remote side executing a hard or abortive close. For UDP sockets, the remote host was unable to deliver a previously sent UDP datagram and responded with a "Port Unreachable" ICMP packet. The application should close the socket as it is no longer usable.

WSAETIMEDOUT

The connection has been dropped, because of a network failure or because the system on the other end went down without notice.

 

Remarks

The send function is used to write outgoing data on a connected socket.

For message-oriented sockets (address family of AF_INET or AF_INET6, type of SOCK_DGRAM, and protocol of IPPROTO_UDP, for example), care must be taken not to exceed the maximum packet size of the underlying provider. The maximum message packet size for a provider can be obtained by callinggetsockopt with the optname parameter set to SO_MAX_MSG_SIZE to retrieve the value of socket option. If the data is too long to pass atomically through the underlying protocol, the error WSAEMSGSIZE is returned, and no data is transmitted.

The successful completion of a send function does not indicate that the data was successfully delivered and received to the recipient. This function only indicates the data was successfully sent.

If no buffer space is available within the transport system to hold the data to be transmitted, send will block unless the socket has been placed in nonblocking mode. On nonblocking stream oriented sockets, the number of bytes written can be between 1 and the requested length, depending on buffer availability on both the client and server computers. The selectWSAAsyncSelect or WSAEventSelect functions can be used to determine when it is possible to send more data.

Calling send with a len parameter of zero is permissible and will be treated by implementations as successful. In such cases, send will return zero as a valid value. For message-oriented sockets, a zero-length transport datagram is sent.

The flags parameter can be used to influence the behavior of the function beyond the options specified for the associated socket. The semantics of the send function are determined by any options previously set on the socket specified in the s parameter and the flags parameter passed to the send function.

Note  When issuing a blocking Winsock call such as send, Winsock may need to wait for a network event before the call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous procedure call (APC) scheduled on the same thread. Issuing another blocking Winsock call inside an APC that interrupted an ongoing blocking Winsock call on the same thread will lead to undefined behavior, and must never be attempted by Winsock clients.

Example Code

The following example demonstrates the use of the send function.

C++
#ifndef UNICODE
#define UNICODE
#endif

#define WIN32_LEAN_AND_MEAN

#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>

// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT 27015

int main() {

    //----------------------
    // Declare and initialize variables.
    int iResult;
    WSADATA wsaData;

    SOCKET ConnectSocket = INVALID_SOCKET;
    struct sockaddr_in clientService; 

    int recvbuflen = DEFAULT_BUFLEN;
    char *sendbuf = "Client: sending data test";
    char recvbuf[DEFAULT_BUFLEN] = "";

    //----------------------
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != NO_ERROR) {
        wprintf(L"WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    //----------------------
    // Create a SOCKET for connecting to server
    ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ConnectSocket == INVALID_SOCKET) {
        wprintf(L"socket failed with error: %ld\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    //----------------------
    // The sockaddr_in structure specifies the address family,
    // IP address, and port of the server to be connected to.
    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );
    clientService.sin_port = htons( DEFAULT_PORT );

    //----------------------
    // Connect to server.
    iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
    if (iResult == SOCKET_ERROR) {
        wprintf(L"connect failed with error: %d\n", WSAGetLastError() );
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
  }

    //----------------------
    // Send an initial buffer
    iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
    if (iResult == SOCKET_ERROR) {
        wprintf(L"send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    printf("Bytes Sent: %d\n", iResult);

    // shutdown the connection since no more data will be sent
    iResult = shutdown(ConnectSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        wprintf(L"shutdown failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    // Receive until the peer closes the connection
    do {

        iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
        if ( iResult > 0 )
            wprintf(L"Bytes received: %d\n", iResult);
        else if ( iResult == 0 )
            wprintf(L"Connection closed\n");
        else
            wprintf(L"recv failed with error: %d\n", WSAGetLastError());

    } while( iResult > 0 );


    // close the socket
    iResult = closesocket(ConnectSocket);
    if (iResult == SOCKET_ERROR) {
        wprintf(L"close failed with error: %d\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    WSACleanup();
    return 0;
}


Example Code

For a another example that uses the send function, see Getting Started With Winsock.

Notes for IrDA Sockets
  • The Af_irda.h header file must be explicitly included.

Windows Phone 8: This API is supported.

Requirements

Minimum supported client

Windows 2000 Professional [desktop apps only]

Minimum supported server

Windows 2000 Server [desktop apps only]

Header

Winsock2.h

Library

Ws2_32.lib

DLL

Ws2_32.dll

转自:http://msdn.microsoft.com/en-us/library/windows/desktop/ms740149(v=vs.85).aspx

WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议,允许客户端和服务器之间高效地传输数据。当遇到 `'send is not a function'` 错误时,通常意味着调用 `send()` 方法的对象并不是一个有效的 WebSocket 实例。 ### 可能的原因及解决方案 #### 1. **确保对象是 WebSocket 实例** 检查调用 `send()` 的对象是否确实是通过 `new WebSocket(url)` 创建的实例。例如: ```javascript const socket = new WebSocket('ws://example.com/socket'); socket.addEventListener('open', (event) => { socket.send('Hello Server!'); // 正确使用 send 方法 [^2] }); ``` 如果尝试在一个非 WebSocket 对象上调用 `send()`,例如一个普通的 JavaScript 对象或未正确初始化的变量,就会出现该错误。 #### 2. **确认连接已打开** WebSocket 的 `send()` 方法只能在连接建立后(即 `readyState === WebSocket.OPEN`)调用。可以在 `open` 事件监听器中发送消息以确保连接已经建立: ```javascript const socket = new WebSocket('ws://example.com/socket'); socket.addEventListener('open', () => { if (socket.readyState === WebSocket.OPEN) { socket.send('Message to server'); } }); ``` 如果在连接尚未建立时调用 `send()`,可能会导致错误或异常。 #### 3. **检查第三方库的封装对象** 如果你使用的是封装了 WebSocket 的库(如 Socket.IO),请查阅文档以了解如何正确调用发送方法。Socket.IO 提供了自己的 API,而不是直接使用原生的 WebSocket 对象: ```javascript const socket = io('http://example.com'); socket.on('connect', () => { socket.emit('message', 'Hello from client'); // 使用 emit 而不是 send [^2] }); ``` 在这种情况下,`send()` 方法可能并不存在,应使用库提供的方法(如 `emit()`)来发送消息。 #### 4. **避免覆盖 WebSocket 实例** 确保没有意外地将 WebSocket 实例覆盖为其他值。例如: ```javascript let ws = new WebSocket('ws://example.com'); ws = 'some string'; // 错误:覆盖了 WebSocket 实例 ws.send('This will throw an error'); // TypeError: ws.send is not a function ``` 这种情况下,原本的 WebSocket 实例被字符串替换,因此无法再调用 `send()`。 #### 5. **检查上下文绑定问题** 在某些框架或异步回调中,`this` 或作用域可能导致引用丢失。确保 `send()` 被正确的 WebSocket 实例调用: ```javascript class ChatClient { constructor() { this.socket = new WebSocket('ws://example.com'); } sendMessage(message) { if (this.socket.readyState === WebSocket.OPEN) { this.socket.send(message); // 确保 this 指向正确 [^2] } } } ``` 如果 `sendMessage` 被作为回调函数传递,可能会导致 `this` 指向错误的对象,从而访问不到 `socket` 属性。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值