一、假如包的长度为Len,需要分x次发送
Len=Len1+Len2+..+Lenx
其实可以这样来发送就可以实现了
1)第一次直接发的内容
包头|Len
Body(Len1)
2)第二次发的
Body(Len2)
3)第X次发的
Body(Lenx)
二、程序简单举例分3次发包
// tcpSend.cpp : 定义控制台应用程序的入口点。
//
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define IPSTR "172.16.40.252"
#define PORT 9080
#define BUFSIZE 1024
int main(int argc, char **argv)
{
int sockfd, ret, i, h;
struct sockaddr_in servaddr;
char str1[4096], buf[BUFSIZE], *str;
char xmlBody[4096];
char xmlBody1[4096];
char xmlBody2[4096];
socklen_t len;
fd_set t_set1;
struct timeval tv;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
printf("创建网络连接失败,本线程即将终止---socket error!\n");
exit(0);
};
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
if (inet_pton(AF_INET, IPSTR, &servaddr.sin_addr) <= 0 ){
printf("创建网络连接失败,本线程即将终止--inet_pton error!\n");
exit(0);
};
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0){
printf("连接到服务器失败,connect error!\n");
exit(0);
}
printf("与远端建立了连接\n");
//要发送的数据
sprintf(xmlBody,"Package sent three times");
sprintf(xmlBody1,"Package");
strcat(xmlBody2," sent three times");
//发送数据
str=(char *)malloc(128);
len = strlen(xmlBody);
sprintf(str, "%d", len);
memset(str1, 0, 4096);
strcat(str1, "POST /test HTTP/1.1\n");
strcat(str1, "Cache-Control: no-cache\n");
strcat(str1, "Pragma: no-cache\n");
strcat(str1, "User-Agent: Java/1.6.0\n");
strcat(str1, "Host: 172.16.40.252:8888\n");
strcat(str1, "Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2\n");
strcat(str1, "Connection: keep-alive\n");
strcat(str1, "Content-Type: application/x-www-form-urlencoded\n");
strcat(str1, "Content-Length: ");
strcat(str1, str);
strcat(str1, "\r\n\r\n");
printf("%s\n",str1);
ret = write(sockfd,str1,strlen(str1));//第一次只有包头,不会有内容
ret = write(sockfd,xmlBody1,strlen(xmlBody1));//第二次发的包的内容
ret = write(sockfd,xmlBody2,strlen(xmlBody2));//第三次发的包的内容
if (ret < 0) {
printf("发送失败!错误代码是%d,错误信息是'%s'\n",errno, strerror(errno));
exit(0);
}else{
printf("消息发送成功,共发送了%d个字节!\n\n", ret);
}
FD_ZERO(&t_set1);
FD_SET(sockfd, &t_set1);
while(1){
sleep(2);
tv.tv_sec= 0;
tv.tv_usec= 0;
h= 0;
printf("--------------->1");
h= select(sockfd +1, &t_set1, NULL, NULL, &tv);
printf("--------------->2");
//if (h == 0) continue;
if (h < 0) {
close(sockfd);
printf("在读取数据报文时SELECT检测到异常,该异常导致线程终止!\n");
return -1;
};
if (h > 0){
memset(buf, 0, 4096);
i= read(sockfd, buf, 4095);
if (i==0){
close(sockfd);
printf("读取数据报文时发现远端关闭,该线程终止!\n");
return -1;
}
printf("%s\n", buf);
}
}
close(sockfd);
return 0;
}
1)可以看到包的内容如下:
2)注意包的内容
<pre name="code" class="html">Content-Length: Len -----这里的N一定要是包的内容长度,如果该Len小于包的body的内容,会导致服务器那边收到的包少几个字符串的