SOCKET网络编程快速上手(二)——细节问题(2)
2.TCP数据包接收问题
对初学者来说,很多都会认为:客户端与服务器最终的打印数据接收或者发送条数都该是一致的,1000条发送打印,1000条接收打印,长度都为1000。但是,事实上并不是这样,发送打印基本不会有什么问题(只是一般情况,如果发生调度或者其他情况,有可能导致差别,因此也要注意封装),接收打印却不是固定的,下面是测试代码:
测试客户端程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define PORT 1234
#define MAXDATASIZE 1000
int main(int argc, char *argv[])
{
int sockfd, num;
char buf[MAXDATASIZE + 1] = {0};
struct sockaddr_in server;
int iCount = 0;
if (argc != 2)
{
printf("Usage:%s <IP Address>
", argv[0]);
exit(1);
}
if ((sockfd=socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf("socket()error
");
exit(1);
}
bzero(&server, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = inet_addr(argv[1]);
if (connect(sockfd, (struct sockaddr *)&server, sizeof(server)) == -1)
{
printf("connect()error
");
exit(1);
}
while (1)
{
memset(buf, 0, sizeof(buf));
if ((num = recv(sockfd, buf, MAXDATASIZE,0)) == -1)
{
printf("recv() error
");
exit(1);
}
buf[num - 1]=' ';
printf("%dth Recv Length: %d
", iCount++, num);
}
close(sockfd);
return 0;
}
TCP客户端
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 #include <string.h> 5 #include <sys/types.h> 6 #include <sys/socket.h> 7 #include <netinet/in.h> 8 #include <netdb.h> 9 10 #define PORT 1234 11 #define MAXDATASIZE 1000 12 13 int main(int argc, char *argv[]) 14 { 15 int sockfd, num; 16 char buf[MAXDATASIZE + 1] = {0}; 17 struct sockaddr_in server; 18 int iCount = 0; 19 20 if (argc != 2) 21 { 22 printf("Usage:%s <IP Address> ", argv[0]); 23 exit(1); 24 } 25 26 if ((sockfd=socket(AF_INET, SOCK_STREAM, 0)) == -1) 27 { 28 printf("socket()error "); 29 exit(1); 30 } 31 bzero(&server, sizeof(server)); 32 server.sin_family = AF_INET; 33 server.sin_port = htons(PORT); 34 server.sin_addr.s_addr = inet_addr(argv[1]); 35 if (connect(sockfd, (struct sockaddr *)&server, sizeof(server)) == -1) 36 { 37 printf("connect()error "); 38 exit(1); 39 } 40 41 while (1) 42 { 43 memset(buf, 0, sizeof(buf)); 44 if ((num = recv(sockfd, buf, MAXDATASIZE,0)) == -1) 45 { 46 printf("recv() error "); 47 exit(1); 48 } 49 buf[num - 1]='