使用UDP插座(C )错误接收数据

Wrong reception of data with UDP socket (C++)

本文关键字:错误 数据 UDP 插座 使用      更新时间:2023-10-16

早上好,

我需要建立UDP连接,以便将客户从客户端发送到服务器。我实现了此示例的连接启动表。

然后我定义了我的client.cc类:

#include <iostream>
#include <string.h>
#include <stdio.h>
#include "udp_client_server.h"
#include "prova.h"
using udp_client_server::udp_client;
#define LDM_IP "127.0.0.1"
#define LDM_PORT 5445       //8000
using namespace std;
int main() {
    cout << "!!!I'm a client!!!" << endl; 
    prova *ciao = new prova() ;
    ciao->a = 86;
    ciao->b = 8.1;
    ciao->c = 90;
    udp_client_server::udp_client *client = new udp_client(LDM_IP, LDM_PORT);
    int b = client->send((char *)ciao,strlen((char *)ciao));
    if (b != strlen((char *)ciao)){
        std::cout<<"Packet corrupted "<< std::endl;
    }
    return 0;
}

然后the sender.cc类:

#include <iostream>
#include <string.h>
#include "udp_client_server.h"
#include "prova.h"
using udp_client_server::udp_server;
#define LDM_IP "127.0.0.1"
#define LDM_PORT 5445       //8000
using namespace std;
int main() {
    cout << "!!!I'm a server!!!" << endl;
    int size_max = 256; 
    udp_client_server::udp_server *server = new udp_server(LDM_IP, LDM_PORT);
    char *buffer;
    int gotMsg = server->recv(buffer,size_max);
    prova *pippo = new prova();
    pippo = (prova *)(buffer);
    std::cout<< "result " << gotMsg <<std::endl;
    std::cout<< "value " << pippo <<std::endl;
    return 0;
}

建立了连接,但我没有得到我发送的内容。在每次运行时,我都会得到不同的错误值,而不是传输的值。

有人可以告诉我错误在哪里?预先感谢

send(.....,strlen((char *)ciao)不发送类

更改您的代码,发送结构变量。

尝试发送(..... sizeof(prova));