发包和接包的步骤
a)发送端:先发送包表示和长度,再发送数据内容。
b)接收端:先解析本次数据包的大小N,再读取N个字节,这N个字节就是一个完整的数据内容。
发送端
a)发送端
const char *TAG= "FBFE";
#define DATA_LEN_BYTES 4:
int ms_len =strlen(message);
int tag_len =strlen(TAG);
buf =(char*)malloc(ms_len+tag_len+DATA_LEN_BYTES);
strcpy(buf,TAG);
*((int *)(buf+tag_len))=ms_len;//这一步是内容长度
memcpy(buf+tag_len+DATA_LEN_BYTES,message,ms_len);
write(sockfd, buf, tag_len+DATA_LEN_BYTES);//先发送包表示和长度,此时buf为FBFE
sleep(3);
//发送数据内容,为输入的值,在memcpy这一步进行了操作,内存赋值
write(sockfd, buf+tag_len+DATA_LEN_BYTES, ms_len);
b)接收端
//改写一下,读数据的函数
int read_package(int client_sock,char *buf,unsigned int len){
int tag_len =strlen(TAG);
int readlen=read(client_sock,buf,tag_len+DATA_LEN_BYTES);
printf("read_len %d\n",readlen);
printf("buf____what is ---- %s\n",buf);
if(strncmp(buf,TAG,tag_len)==0){ //先判断第一次的buf是否符合
printf("合法buf____what is ---- %s\n",buf);
int data_len=*((int *)(buf+tag_len)); //获得读的长度
printf("data length:%d\n",data_len);
int count =0;
readlen =0;
while(count<data_len){
readlen=read(client_sock,buf,data_len-count);
printf("readlen: %d\n",readlen);
count +=readlen;
}
return data_len;
}
}