使用UDP传输对象b / w客户端/服务器

时间:2014-11-30 18:24:35

标签: c++ udp client-server

我想从服务器向客户端发送一个对象。通过UDP。在c ++中。我试图简单地发送一个对客户端的引用,并在客户端做一个指针来引用这个地址。我尝试的代码是:

数据:

class data
{
private:
    int number;
public:
    data(int number) {
        this->number = number;
    }
    void print() {
        cout<<"number : "<<number;
    }
};

服务器:

data *obj;
if (recvfrom(conn_sock, obj, sizeof(data), 0, (struct sockaddr*)&client_addr, &slen) == -1)
    cout<<"ERROR: recvfrom()";
else cout<<"SUCCESS: recvfrom()";

cout<<"\nRECEIVED from Client : ";
obj->print();

客户端:

data *obj = new data(11);
if(sendto(conn_sock, &obj, sizeof(data), 0, (struct sockaddr*)&serv_addr, addr_len) == -1)
    cout<<"ERROR: Problem sending data";
else cout<<"SUCCESS: sending object";

1 个答案:

答案 0 :(得分:0)

解决了,问题。就像@snixtho建议的那样。工作代码是:

数据:

class data
{
private:
    int number;
    float gpa;
public:
    data(int number, float gpa) {
        this->number = number;
    }
    void print() {
        cout<<"number : "<<number<<"gpa : "<<gpa;
    }
    int getNumber() {
        return this->number;
    }
    int getGpa() {
        return this->number;
    }
};

服务器:

data *obj;
int number = 0;
float gpa = 0.0;

if (recvfrom(conn_sock, buf, buff_length, 0, (struct sockaddr*)&client_addr, &slen) == -1)
    cout<<"ERROR: recvfrom()";
number = atoi(buf);

if (recvfrom(conn_sock, buf, buff_length, 0, (struct sockaddr*)&client_addr, &slen) == -1)
    cout<<"ERROR: recvfrom()";
gpa = atoi(buf);

obj = new data(number, gpa);

cout<<"\nRECEIVED from Client : ";
obj->print();
cout<<"\n\n";

客户端:

data *obj = new data(11, 3.2);
int n=0;    // n is the number of bytes of 'buf' after converting the integer to 'buf'

n = sprintf(buf, "%d", obj->getNumber());  
if(sendto(conn_sock, buf, buff_length, 0, (struct sockaddr*)&serv_addr, addr_len) == -1)
    cout<<"ERROR: Problem sending data";

n = sprintf(buf, "%f", obj->getGpa());
if(sendto(conn_sock, buf, buff_length, 0, (struct sockaddr*)&serv_addr, addr_len) == -1)
    cout<<"ERROR: Problem sending data";

这是解决问题的方法,但我确信还有其他更好的方法可以做到这一点。