码迷,mamicode.com
首页 > Web开发 > 详细

关于Http通信

时间:2015-07-25 12:04:16      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

虽然是做android开发,但网络通信这块还是习惯用C语言来实现,主要有如下原因:

1,不利于封装命令请求

2,写好这个模块后,通过JNI调用很是方便,复用也方便

技术分享
 1 const char* connectTrafficData(const char* cmd) {
 2      LOGD("-----------connectTrafficData-------------");
 3         int length;
 4         int sockfd;  
 5         int len;    
 6         struct sockaddr_in address;  
 7         int result;  
 8         char httpstring[1024] = {0};                  
 9         char response[1024] = {0};
10     
11         strcpy(httpstring,cmd);
12         strcat(httpstring,"\n");
13         sockfd = socket(AF_INET, SOCK_STREAM, 0);  
14         address.sin_family = AF_INET;  
15         address.sin_addr.s_addr = inet_addr("127.0.0.1");  
16         address.sin_port = htons(23633); 
17         len = sizeof(address); 
18         
19         struct timeval timeout={2,0};
20         setsockopt(sockfd,SOL_SOCKET,SO_RCVTIMEO,(char*)&timeout,sizeof(struct timeval));
21         
22         result = connect(sockfd,(struct sockaddr *)&address,len);  
23         if(result == -1){   
24             LOGD("connect_result=-1");
25             strcpy(response,"-1");
26             close(sockfd);
27             
28         } 
29         
30         if ( send(sockfd,httpstring,strlen(httpstring),0) < 0 ) {
31             LOGD("send response failed.\n");
32             strcpy(response,"-1");
33             close(sockfd);
34                     
35         }
36             
37         length = recv(sockfd,response,MAXSIZE,0);
38         if (length < 0) {
39         
40             LOGD("\n recv_length < 0\n"); 
41             strcpy(response,"-1");
42             close(sockfd);
43             
44         }else{
45         
46             LOGD(response); 
47             
48         }
49         return response;
50 }
View Code

 

关于Http通信

标签:

原文地址:http://www.cnblogs.com/Miami/p/4675501.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!