简体   繁体   English

如何通过套接字发送 int?

[英]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.我正在使用 C++ 学习非常基本的套接字编程,我被困在试图通过套接字发送随机生成的 int 的部分。

server.cpp服务器.cpp

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

client.cpp客户端.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. sockets 是臭名昭著的(本质上)容易出错。

  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.假设所有字节都将一起发送和接收 - 但 TCP 容易出现分段、碎片、部分发送和各种你不应该假设你会在一次调用中收到所有发送的东西。 Which makes it even more important to check the return value!这使得检查返回值变得更加重要!

  3. That cast you do: (char*)code is incorrect.你做的那个演员: (char*)code不正确。 More appropriate to do (char*)&code , but it doesn't recognize partial receives.更适合做(char*)&code ,但它不识别部分接收。

Assuming you are using a TCP socket:假设您使用的是 TCP 套接字:

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.对于 UDP 套接字,一些原则在错误检查、投射到/从 memory 缓冲区方面保持不变。 But with UDP you should not do the "looping" thing since UDP is a datagram protocol.但是对于 UDP 你不应该做“循环”的事情,因为 UDP 是一个数据报协议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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