聊天室程序。
我在客户端用结构体保存登陆信息发到服务器。如下:
struct logInfo
{
char *name;
char *pwd;
char *intro;
}调用send的时候要知道发送的长度,但是我的每个字段内容长度都是运行时分配的。怎么获得长度?运行时候示例:
logInfo li;
li.name = new char[64];
li.intro = new char[1024];
每个字段长度要运行时才能确定。怎么处理?
我在客户端用结构体保存登陆信息发到服务器。如下:
struct logInfo
{
char *name;
char *pwd;
char *intro;
}调用send的时候要知道发送的长度,但是我的每个字段内容长度都是运行时分配的。怎么获得长度?运行时候示例:
logInfo li;
li.name = new char[64];
li.intro = new char[1024];
每个字段长度要运行时才能确定。怎么处理?
编码的方法,提供一种 参考:
name length: 2 Bytes;
name content: [n bytes];
pwd length: 2 bytes;
pwd content: [n bytes];
intro length: 2 bytes;
intro content: [n bytes];固定结构:
struct logInfo
{
char name[20]; // 假设定义的长度足够容纳最长的信息(即: 这里的name永远不会超过20 bytes
char pwd[20];
char intro[256];
};这样可以直接发送整个结构, 接收也是接收一整个结构:logInfo linfo;
strcpy(linfo.name, "krh2001");
strcpy(....);
....int n = send(s, &linfo, sizeof(logInfo), 0);接收:logInfo linfo;int n = recv(s, &linfo, sizeof(logInfo), 0);if(n == sizeof(logInfo))
{
// 收到完整消息
// process...
}
struct logInfo
{
char *name;
int namelen;
char *pwd;
int pwdlen;
char *intro;
itn introlen;
}
你在实际传输时需要传输实际数据
为了在接收方能够正确的解析数据,可以对每个字段加上一个长度信息来传送,例如:
帧长度 | name长度 | name | pwd 长度 | pwd | intro长度 | intro
你可以先接收帧长度,再根据帧长度来recv一次就可以