简体   繁体   中英

How to send int over the socket?

I'm learning very basic socket programming with C++ I'm stuck at the part where I'm trying to send a randomly generated int over the socket.

server.cpp

int code = rand();
send(connfd, (char*)code, sizeof(int), 0);

client.cpp

int code = 0;
recv(connfd, (char*)code, sizeof(int), 0);

What am I doing wrong?

For starters:

  1. You are not checking the return value from either of your calls. sockets are notorious (by nature) error prone.

  2. Assuming all bytes will be sent and received together - but TCP is prone to segmentation, fragmentation, partial sends, and all sorts of stuff where you should never assume you'll receive everything sent in one call. Which makes it even more important to check the return value!

  3. That cast you do: (char*)code is incorrect. More appropriate to do (char*)&code , but it doesn't recognize partial receives.

Assuming you are using a TCP socket:

Send:

int data = rand();
char* tosend = (char*)&data;
int remaining = sizeof(data);
int result = 0;
int sent = 0;
while (remaining > 0) {
    result = send(connfd, tosend+sent, remaining, 0);
    if (result > 0) {
        remaining -= result;
        sent += result;
    }
    else if (result < 0) {
        printf("ERROR!\n");
        // probably a good idea to close socket
        break;
    }
}

Receive:

int value = 0;
char* recv_buffer = (char*)&value;
int remaining = sizeof(int);
int received = 0
int result = 0;
while (remaining > 0) {
    result = recv(connfd, recv_buffer+received, remaining, 0);
    if (result > 0) {
        remaining -= result;
        received += result;
    }
    else if (result == 0) {
        printf("Remote side closed his end of the connection before all data was received\n");
        // probably a good idea to close socket
        break;
    }
    else if (result < 0) {
        printf("ERROR!\n");
        // probably a good idea to close socket
        break;
    }
}

For a UDP socket, some of the principals remaining the same with regards to error checking, casting to/from memory buffers. But with UDP you should not do the "looping" thing since UDP is a datagram protocol.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM