如何在C ++中使用TCP/IP套接字发送结构 [英] How to send structure using TCP/IP socket in c++(windows)

查看:98
本文介绍了如何在C ++中使用TCP/IP套接字发送结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我想使用TCP/IP套接字程序将结构指针从客户端发送到服务器.
我得到了输入指针并发送的指导.
但这不起作用.
我想我不知道键入强制转换结构指针的实际步骤.

如果知道的话,请给我一个主意.

谢谢.

Hello,

I want to send structure pointer from client to server using TCP/IP socket program.
I got a guidance to type cast my pointer and send.
But it''s not working.
I think I don''t know the actual step to type cast structure pointer.

If you know, Please give me an idea to do it..

Thank you.

推荐答案

这取决于您结构的内容,但您需要对数据进行序列化/反序列化,可能逐字段进行.如果您的客户端和服务器都具有相同的字节序",则这很简单,但是如果它们不同,则可能需要使用xtonx()函数,如
It depends on the content of your structure but you need to serialize/deserialize your data, probably field by field. If both your client and server have the same "endian-ness" this is fairly simple, but if they are different then you may need to use the xtonx() functions as described here[^].


投射指针是...叫猫狗".
您实际上可以称呼狗"为猫,但它不会开始吠叫.

强制转换指针是没有意义的:指针仅包含本地进程空间的内存地址.一旦将该地址转移到另一台机器(或进程或其他机器)上,它将如何处理?

您必须发送数据(而不是指针)并在另一侧重建指针,因此需要序列化".
现在是时候停下来学习有关该概念的更多信息了.
不能满足快速解答"的要求.
Casting the pointer is ... calling "dog" a cat.
You can actually call "dog" a cat, but it will not start barking.

Casting the pointer is ... pointless: a pointer contain just an address of the memory of your local process space. Once you transfered that address to the other machine (or process or whatever) what could it do with it?

You have to send the data (not the pointers) and reconstruct the pointers on the other side, hence "serialization" is needed.
It is time to stop and learn something more on that concept.
Not something that can fit a "quick answer".




我相信您正在使用winsock2进行套接字编程,如果您在服务器中使用send函数调用,这是我的示例代码:

Hi,

I believe you are using winsock2 for socket programming,if you are using send function call in the server this is the sample code by me:

struct myStruct {
        int a,b;
    }myStruct1;
    void* myPtr = &myStruct1;
    send(client,(char*)myPtr,sizeof(myStruct1),0);





在客户端代码中,您可以将其类型转换回所需的结构类型.





In client side code you can typecast it back to the required struct type.


这篇关于如何在C ++中使用TCP/IP套接字发送结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆