簡體   English   中英

如何通過套接字發送 int?

[英]How to send int over the socket?

我正在使用 C++ 學習非常基本的套接字編程,我被困在試圖通過套接字發送隨機生成的 int 的部分。

服務器.cpp

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

客戶端.cpp

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

我究竟做錯了什么?

對於初學者:

  1. 您沒有檢查任何一個調用的返回值。 sockets 是臭名昭著的(本質上)容易出錯。

  2. 假設所有字節都將一起發送和接收 - 但 TCP 容易出現分段、碎片、部分發送和各種你不應該假設你會在一次調用中收到所有發送的東西。 這使得檢查返回值變得更加重要!

  3. 你做的那個演員: (char*)code不正確。 更適合做(char*)&code ,但它不識別部分接收。

假設您使用的是 TCP 套接字:

發送:

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;
    }
}

收到:

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;
    }
}

對於 UDP 套接字,一些原則在錯誤檢查、投射到/從 memory 緩沖區方面保持不變。 但是對於 UDP 你不應該做“循環”的事情,因為 UDP 是一個數據報協議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM