zoukankan      html  css  js  c++  java
  • 关于Http通信

    虽然是做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,"
    ");
    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.
    ");
    32             strcpy(response,"-1");
    33             close(sockfd);
    34                     
    35         }
    36             
    37         length = recv(sockfd,response,MAXSIZE,0);
    38         if (length < 0) {
    39         
    40             LOGD("
     recv_length < 0
    "); 
    41             strcpy(response,"-1");
    42             close(sockfd);
    43             
    44         }else{
    45         
    46             LOGD(response); 
    47             
    48         }
    49         return response;
    50 }
    View Code
  • 相关阅读:
    Spring Boot JDBC 使用教程
    Spring Boot FreeMarker 使用教程
    椭圆曲线ECC ECDH原理&& javacard实现
    java中的强制类型转换:int和byte
    JUnit学习
    java异常处理
    Maven使用
    哈希表问题
    计数排序
    链表Linked List
  • 原文地址:https://www.cnblogs.com/Miami/p/4675501.html
Copyright © 2011-2022 走看看