本次代码涉及到的内容:socket通讯,文件读取

读取的文件以及文件位置:

   要读取的文件和c文件在同一个目录下。客户端(client)读取的是123.xml,服务端(server)读取的是23.xml。

  

头文件( mysocket.h):

 1 /* File Name:  mysocket.h*/  
 2 #include<stdio.h>  
 3 #include<stdlib.h>  
 4 #include<string.h>  
 5 #include<errno.h>  
 6 #include<sys/types.h>  
 7 #include<sys/socket.h>  
 8 #include<netinet/in.h>
 9 
10 /*
11 FunName:getFileAll
12    Desc:get the file content
13    Para:[fname] filename pointer
14  Return:1.[*pBuf] file content pointer
15         2.[*length] file length 
16 */
17 char *getFileAll(char *fname,int *length)
18 {
19     int  fileLight = 0;
20     char *pBuf;                  //定义文件指针    
21     FILE *pFile;
22     
23     pFile = fopen(fname,"r");    //获取文件的指针
24     if(pFile == NULL)
25     {
26         printf("\nOpen file %s fail\n",pFile);
27         return    NULL;    
28     }
29 
30     fseek(pFile,0,SEEK_END);      //把指针移动到文件的结尾 ,获取文件长度
31     fileLight = ftell(pFile);     //获取文件长度
32     pBuf =(char *)malloc(fileLight);  
33       rewind(pFile);                 //把指针移动到文件开头 因为我们一开始把指针移动到结尾,如果不移动回来 会出错
34     fread(pBuf,1,fileLight,pFile); //读文件
35     pBuf[fileLight]=0;             //把读到的文件最后一位 写为0 要不然系统会一直寻找到0后才结束
36       fclose(pFile);                 // 关闭文件    
37     *length = fileLight;
38     return pBuf;
39 }

 

服务端(cservice.c):

 1 /* File Name: cservice.c */  
 2 #include "mysocket.h"  
 3 
 4 #define DEFAULT_PORT 8000  //监听端口号
 5 #define MAXLINE 4096  
 6 
 7 int main(int argc, char** argv)  
 8 {  
 9     int    socket_fd, connect_fd;  
10     int        length;            //file content Light
11     struct sockaddr_in     servaddr;  
12     char    buff[4096];  
13     int     n;  
14     char *p;  
15     char *fname="./23.xml";
16     if( (socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ) //初始化Socket  
17     {  
18         printf("create socket error: %s(errno: %d)\n",strerror(errno),errno);  
19         exit(0);  
20     }  
21     //初始化  
22     memset(&servaddr, 0, sizeof(servaddr));  
23     servaddr.sin_family = AF_INET;  
24     servaddr.sin_addr.s_addr = htonl(INADDR_ANY);             //IP地址设置成INADDR_ANY,让系统自动获取本机的IP地址。  
25     servaddr.sin_port = htons(DEFAULT_PORT);                  //设置的端口为DEFAULT_PORT    
26                                                                          
27     if( bind(socket_fd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1)   //将本地地址绑定到所创建的套接字上 
28     {  
29         printf("bind socket error: %s(errno: %d)\n",strerror(errno),errno);  
30         exit(0);  
31     }  
32     
33     if( listen(socket_fd, 10) == -1)                  //开始监听是否有客户端连接 
34     {  
35         printf("listen socket error: %s(errno: %d)\n",strerror(errno),errno);  
36         exit(0);  
37     }  
38     printf("======waiting for client\'s request======\n");  
39     while(1)
40     {    
41         if( (connect_fd = accept(socket_fd, (struct sockaddr*)NULL, NULL)) == -1)  //阻塞直到有客户端连接,不然多浪费CPU资源。
42         {  
43             printf("accept socket error: %s(errno: %d)",strerror(errno),errno);  
44             
45             continue;  
46         }  
47 
48         n = recv(connect_fd, buff, MAXLINE, 0);  //接受客户端传过来的数据  
49         buff[n] = \'\0\';  
50         printf("recv msg from client:\n%s\n", buff); 
51 
52         p = getFileAll(fname,&length);
53         if( p == NULL )
54         {
55             printf("open file error!");  
56             exit(0);
57         }
58         if(!fork())               //向客户端发送回应数据  
59         {         
60             if( send(connect_fd, p, length, 0) < 0)  
61             {  
62                 printf("send msg error: %s(errno: %d)\n", strerror(errno), errno);                   
63             }    
64             close(connect_fd);     
65             exit(0);         
66         }          
67         close(connect_fd);        
68     }  
69     close(socket_fd);  
70     
71 }  

客户端(cclient.c)

 1 /* File Name: cclient.c */  
 2   
 3 #include "mysocket.h"  
 4 
 5 #define MAXLINE 4096 
 6 
 7 
 8   
 9 int main(int argc, char** argv)  
10 {  
11     int    sockfd, n,rec_len;
12     int        length;            //file content Light
13     int     i_port = 8000;     //default 8000 port
14     
15     char    recvline[4096];
16     char    buf[MAXLINE];  
17     char    *c_ipAddr = "127.0.0.1"; //ip addr
18     char     *p;                //file content     
19     char    *fname="./123.xml";  //file name
20     
21     struct sockaddr_in    servaddr;      
22   
23     if( argc == 1)
24     {
25         printf("This client will connect server message: IP=127.0.0.1 , Port=8000 \n");        
26     }
27     else if( argc ==2 )
28     {
29         c_ipAddr = argv[1];
30         printf("This client will connect server message: IP=%s , Port=8000 \n",c_ipAddr);    
31     }
32     else if( argc == 3)
33     {
34         c_ipAddr = argv[1];    
35         i_port = atoi(argv[2]);
36         printf("This client will connect server message: IP=%s , Port=%d \n",c_ipAddr, i_port);    
37     }
38     else
39     {  
40         printf("usage: ./client <ipaddress> and port \n");  
41         exit(0);  
42     }  
43   
44       
45     if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
46     {  
47         printf("create socket error: %s(errno: %d)\n", strerror(errno),errno);  
48         exit(0);  
49     }    
50   
51     memset(&servaddr, 0, sizeof(servaddr));  
52     servaddr.sin_family = AF_INET;  
53     servaddr.sin_port = htons(i_port);  
54     
55     if( inet_pton(AF_INET, c_ipAddr, &servaddr.sin_addr) <= 0)
56     {  
57         printf("inet_pton error for %s\n",argv[1]);  
58         exit(0);  
59     }  
60   
61     if( connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
62     {  
63         printf("connect error: %s(errno: %d)\n",strerror(errno),errno);  
64         exit(0);  
65     }  
66     
67     p = getFileAll(fname,&length);
68     if( p == NULL )
69     {
70         printf("open file error!");  
71         exit(0);
72     }
73     
74     if( send(sockfd, p, length, 0) < 0)  
75     {  
76         printf("send msg error: %s(errno: %d)\n", strerror(errno), errno);  
77         exit(0);  
78     }  
79     if((rec_len = recv(sockfd, buf, MAXLINE,0)) == -1)
80     {  
81        perror("recv error");  
82        exit(1);  
83     }  
84     
85     buf[rec_len]  = \'\0\';  
86     printf("Received :\n%s\n",buf);  
87     close(sockfd);  
88     exit(0);  
89 }  

makefile:

 1 all: server client
 2 .PHONY:all
 3 
 4 client:client.o
 5     gcc client.o -o client
 6 client.o:cclient.c
 7     gcc -c cclient.c  -o client.o
 8 server:server.o
 9     gcc server.o -o server
10 server.o:cservice.c
11     gcc -c cservice.c -o server.o
12 
13 .PHONY:clean
14 
15 clean:            
16     rm -rf *.o
17     rm -rf server client

123.xml 文件:

1 <field name="123.xml" value="123"/>
2 <field name="123test" value="123test"/>

23.xml文件:

1 <body>
2 <name>server</name>
3 </body>

编译:

  执行 make 命令就会有 client,server 了。在两个窗口分别执行如下结果:

      

  

  

版权声明:本文为mingyue605原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/mingyue605/p/8810913.html