socket字符流循环截取

场景:socket 客户端将一个单向链表序列化后发送给服务端,服务端将之解析,重新构建单向链表。

Client.cpp

 //遍历链表,填充到缓冲区
char* formatBuf(ListNode* p, char buf[])
{
ListNode* tmp = p;
//处理空链表
if (tmp == NULL)
{
std::cout << "空链表!" << std::endl;
}
memset(buf, , sizeof(buf));
while (tmp->next != NULL)
{
tmp = tmp->next;
//填充到缓冲区
char tmpStr[];
sprintf(tmpStr, "%s/%s/%d ", tmp->Name, tmp->ID, tmp->Score);
strcat(buf, tmpStr);
}
return buf;
}

Server.cpp

 //字符流解析
void parseStr(char* buf, int len)
{
//新建链表
ListNode *head, *node, *ptr;
head = (ListNode*)malloc(sizeof(ListNode));
int i =, count = ;
char* p = buf;//offset ptr
ptr = head;
while(p < buf + len)
{
char name[];
char id[];
unsigned int s;
//字符串截取
sscanf(p, "%1s/%5s/%d", name, id, &s);
//printf("%s %s %d \n", name, id, s);
//申请空间
node = (ListNode*)malloc(sizeof(ListNode));
strcpy(node->Name, name);
strcpy(node->ID, id);
node->Score = s;
ptr->next = node;
node->next = NULL;
ptr = node; p += ;//指针偏移
}
printList(head);
}

参考资料

【1】https://ask.csdn.net/questions/370828  (二楼回答,我根据回答修改的)

上一篇:windows phone (17) ManipulationDelta事件


下一篇:移动端,input输入框被手机输入法解决方案