2017-02-21 140 views
-1

早上好数据,接收错误与UDP套接字(C++)

我需要建立,以便从客户端发送一些数据到服务器的UDP连接。我从这个example开始实施连接。

然后我定义我的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; 
} 

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

的连接建立,但我没有得到什么,我送。在每次运行中,我都会得到一个不同的错误值,而不是传送的值。

任何人都可以告诉我错误在哪里? 在此先感谢

+0

有没有这样的事情作为UDP连接。 – EJP

+0

@EJP你是什么意思? – moi

回答

1

发送(.....,strlen的((字符*)的Ciao) 犯规送类

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

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

+0

它的工作!非常好 – moi