Send and Receive data via Socket

Asked

Viewed 530 times

0

I am beginner in socket, I would like to know what is the best way to send and receive data. I would like a better explanation about how it works.

1 answer

2


(Based on data from MSDN)

send Function

  • The function send sends data to a connected socket.

    int send( In SOCKET s, In const char *buf, In int Len, In int flags );

s[in] An identification descriptor for the connected socket

buffet[in] A pointer to the buffer containing the data to be transmitted

Len[in] The Length, in bytes, of the data contained in buffer pointed by the parameter buffet

flags[in] Specifies the way the call is made.

Return Value: If no error occurs, the send function returns the total number of bytes sent. Otherwise, a value of SOCKET_ERROR is returned, the error code can be recovered by calling Wsagetlasterror.

Example:

int iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
    if (iResult == SOCKET_ERROR) 
    {
            wprintf(L"Send Falhou, codigo de erro %d\n", WSAGetLastError());
            closesocket(ConnectSocket);
            WSACleanup();
            return 1;
     }

recv Function

  • The function recv receives data from a connected socket or a socket without a connected connection

int recv( In SOCKET s, Out char *buf, In int Len, In int flags );

s[in] An identification descriptor for the connected socket

buffet[out] A pointer to the buffer to receive input data.

Len[in] The Length, in bytes, of the data contained in buffer pointed by the buf parameter

flags[in] A set of flags that influence the behavior of this function.

Return Value:

If there is no error the recv function returns the number of bytes received and the buffer aimed at the buf parameter will contain the received data. If the connection was terminated normally, the return value is zero.

Otherwise, a value of SOCKET_ERROR is returned, the error code can be recovered by calling Wsagetlasterror.

Example:

int iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
        if ( iResult > 0 )
            printf("Bytes Recebidos: %d\n", iResult);
        else if ( iResult == 0 )
            printf("Conexao encerrada.\n");
        else
            printf("recv falhou, codigo de erro: %d\n", WSAGetLastError());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.