spyker10
spyker10

Reputation: 129

Winsock send a string

I will try to send a string like "hello world" to the client,but I can only send the first part of "hello" in a vector char [],how can I send a string?

send(client, win, strlen(win), 0);

win is a char [], can be a string?

the complete code is:

  int main(int argc, const char* argv[])
{
    WSADATA wsadata;
    int error = WSAStartup (0x0202, &wsadata);
    if(error == 1) return 1;
    std::cout << "WSA started";
    SOCKET connessione;
    sockaddr_in target;
    target.sin_family = AF_INET;
    target.sin_port = htons (9000);
    target.sin_addr.s_addr = inet_addr("127.0.0.1");
    target.sin_port = htons((u_short)9001);
    connessione = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (connessione == INVALID_SOCKET) 
    { 

        std::cout << "Error socket";
        system("pause>null");
        return INVALID_SOCKET; 
    }
    std::cout << "\nSocket create";
    if(bind(connessione, (sockaddr*)&target, sizeof(target)) != 0) return 0;
    if(listen(connessione, 10) != 0) return 0;
    SOCKET client;
    sockaddr_in from;
    int fromlen = sizeof(from);
    std::cout << "\nWait the client connection...";
    client = accept(connessione, (sockaddr*)&from, &fromlen);
    std::cout << "\nClient connect";
    std::string win;

    std::cout << "\n\nInsert text to send: ";
    std::cin >> win;

    send(client, win, strlen(win), 0);
    std::cout << "\ntext send ok. FINE";
    Sleep(2000);
    system("pause>null");
    closesocket(connessione);
    closesocket(client);
    WSACleanup();
    return 0;
}

Upvotes: 3

Views: 5082

Answers (1)

Mart&#237;nV
Mart&#237;nV

Reputation: 184

Conversion to a char array may be what you're looking for:

send(client, win.c_str(), win.size(), 0);

Also as already mentioned, you should check for return values (to detect any possible error) and keep in mind that send and recv don't always send/receive all the data on the first try (you have to loop until the entire data is sent/received).

Edit: the >> operator stops reading when it sees a separator (space, newline, etc). If you want to read the whole line you could do for example:

std::getline(std::cin, win);

Upvotes: 3

Related Questions