struct aaa {
int len;//这个是记录pt分配的长度
char* pt;//由于pt是变长的所以我用指针
}; aaa str;
str.pt = new char[100];
strcpy(str.pt, "hello the world");
str.len = strlen(str.pt); byte* psend = new byte[sizeof(str)+str.len];
memcpy(psend, &str, sizeof(str));
memcpy(psend+sizeof(str), str.pt, str.len); send(sk, (char*)psend, sizeof(str)+str.len, 0);aaa a;
int len = recv(from[i], (char*)&a, sizeof(a), 0);//这里我先接收结构体,从而获得串的长度,
len = recv(from[i], pt, a.len, 0);//通过长度把剩余的数据接收,但是pt里的内容不是"hello the world",为什么,哪里错了?
int len;//这个是记录pt分配的长度
char* pt;//由于pt是变长的所以我用指针
}; aaa str;
str.pt = new char[100];
strcpy(str.pt, "hello the world");
str.len = strlen(str.pt); byte* psend = new byte[sizeof(str)+str.len];
memcpy(psend, &str, sizeof(str));
memcpy(psend+sizeof(str), str.pt, str.len); send(sk, (char*)psend, sizeof(str)+str.len, 0);aaa a;
int len = recv(from[i], (char*)&a, sizeof(a), 0);//这里我先接收结构体,从而获得串的长度,
len = recv(from[i], pt, a.len, 0);//通过长度把剩余的数据接收,但是pt里的内容不是"hello the world",为什么,哪里错了?
不过我觉得你不用那么吝惜内存,现在的内存都好大的,你的代码可以改成一下这样
char buf[1024*1024];
sprintf(&buf[4], "Hello world");
int len = *(int *)buf = strlen(&buf[4]);
send(sk, buf, len+4, 0);
len = recv(form[i], buf, sizeof(int), 0);
len = recv(from[i], &buf[4], *(int *)buf, 0); //如果数据很多一次就收不完了,要收多次。
接受时:ntohs
把你的接收的代码贴出来给我看看。
我按照你的传输方式写的:
char rbuf[32];
int recvbyte = 0;
memset(rbuf, 0, 32);
aaa recvbuf;
recvbuf.length = 0;
recvbuf.pt = NULL;
recvbyte = recv(clientS, (char*)&recvbuf, sizeof(recvbuf), 0);
recvbuf.pt = rbuf;
recvbyte = recv(clientS, recvbuf.pt, recvbuf.length, 0 );
cout << "接收的字符串为" << recvbuf.pt << endl;
int len = recv(from[i], (char*)&a, sizeof(a), 0);//这里我先接收结构体,从而获得串的长度,
len = recv(from[i], pt, a.len, 0);//通过长度把剩余的数据接收,但是pt里的内容不是"hello the world",为什么,哪里错了?
---------------------------------------------int len = recv(from[i], (char*)&a, sizeof(a), 0);这里 a.pt 被初始化了。这个地址是否有效不确定。如果a.pt被初始化为 NULL
的话,你后面继续recv肯定有问题。
常用的方法是
struct aaa
{
int len;
char data[1];
//为了字节对齐,这里最好是填充 3 个char
};
aaa a;
int len = recv(from[i], (char*)&a, sizeof(a), 0);
楼主首先接收的长度是结构体的长度,所以这点没有问题