SOCKET 变长结构体

SOCKET发送结构体时,必须使用连续的内存。也就是结构内(嵌套)不能包含指针。

发送时将结构体转为字节流

1. 定长结构体

  1. struct Sendbuf
  2. {
  3.     char SendDate[1024]; //定长的数据
  4. };
  5.   
  6. const char *msg = "Think You!!!"; //这里是要发送的内容 

  7. int SendDateklength = sizeof(Sendbuf) + strlen(msg)+1; //计算要发送的总的长度 (结构体长度+发送内容的长度)
  8. Sendbuf SendDate; 

  9. SendDate.length = strlen(msg); 
  10. strcpy_s(SendDate.SendDate,strlen(msg) + 1,msg); 

//将结构体首地址转为(const char*),发送

  1. send(socket,(const char *)&SendDate,SendDateklength,0)
2. 变长结构体

  1.     struct Sendbuf
  2.     { 
  3.         char sendDataWarning[0]//VS2010: warning C4200: 使用了非标准扩展 : 结构/联合中的零大小数组.
  4.                                 //   当 UDT 包含大小为零的数组时,无法生成复制构造函数或副本赋值运算符
  5.         char SendDate[1]; //未知长度的数据
  6.         int length; //发送数据的长度
  7.     };
  8.     const char *msg = "Think You!!!"; //这里是要发送的内容(msg是未知大小的内容)
  9.     int SendDateklength = sizeof(Sendbuf) + strlen(msg) +1; //计算要发送的总的长度 (结构体长度+发送内容的长度) 

  10.     Sendbuf *SendDate = (Sendbuf*)new char[SendDateklength ]; //申请待发送的数据的实际长度
  11.     SendDate->length = strlen(msg);
  12.     strcpy_s(SendDate->SendDate,strlen(msg) + 1,msg); //这里使用strcpy_s赋值 

  13.     send(socket,(const char *)SendDate,SendDateklength,0); //Send
  14.     delete []SendDate; //发送完之后记得释放内存
//参考
http://blog.csdn.net/zhaobangyu/article/details/8904005

<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
阅读(1686) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~
评论热议
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kelsel

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值