接上一篇:iMX257开发板连接internet的过程 (http://blog.csdn.net/tyshtang/article/details/43722831)
目标是模仿一个Arduino项目:Ulink——基于微信的物联网平台 (http://www.arduino.cn/thread-7368-1-1.html)
iMX257代码如下。
存在一个已知问题:tcp 套接字编程是阻塞式的,网络不能保证畅通,如果connect,write, read 任何一个失败,程序就运行不下去了。
//TCP示例客户端 tcpclt.c
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "lm35.h" int main() { int skfd; char buf[1024] = {0}; struct sockaddr_in server_addr; struct hostent *host; int portnumber,nbytes; int sensrdata = 0; char sensrdata2[10]; int sensrdatalen; /* sensrdata = lm35_fun(); sensrdatalen = sprintf(sensrdata2,"%d",sensrdata); char httpreq_data[sensrdatalen]; sscanf(sensrdata2,"%[1-9]",httpreq_data); */ char httpreq_1[] = "GET /downup.php?token=doubleq&data="; char httpreq_2[] = " HTTP/1.1\r\nHost: 1.tangerlink2.sinaapp.com\r\n\ User-Agent: arduino-ethernet\r\nConnection: close\r\n\r\n"; char sinaserver[] = "1.tangerlink2.sinaapp.com"; portnumber = 80; /* char send_data[] = "GET /downup.php?token=doubleq&data=11 HTTP/1.1\r\nHost: 1.tangerlink2.sinaapp.com\r\n\ User-Agent: arduino-ethernet\r\nConnection: close\r\n\r\n"; */ if(NULL == (host=gethostbyname(sinaserver)))/*DNS解析*/ { perror("Gethostname error:"); exit(1); } /* 客户端填充需要连接的服务器的地址信息结构体 */ bzero(&server_addr,sizeof(server_addr)); server_addr.sin_family=AF_INET; server_addr.sin_port=htons(portnumber); server_addr.sin_addr=*((struct in_addr *)host->h_addr); printf("My server IP Address %s\r\n" , inet_ntoa(server_addr.sin_addr)); while(1) { sensrdata = lm35_fun(); sensrdatalen = sprintf(sensrdata2,"%d",sensrdata); char httpreq_data[sensrdatalen]; sscanf(sensrdata2,"%[1-9]",httpreq_data); /* 创建socket描述符 */ if(-1 == (skfd=socket(AF_INET,SOCK_STREAM,0))) { perror("Socket Error:"); exit(1); } /* 客户端调用connect主动发起连接请求 */ if(-1 == connect(skfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr))) { perror("Connect Error:"); exit(1); } if(-1 == write(skfd,httpreq_1,strlen(httpreq_1))){ perror("Send error:"); } if(-1 == write(skfd,httpreq_data,strlen(httpreq_data))){ perror("Send error:"); } if(-1 == write(skfd,httpreq_2,strlen(httpreq_2))){ perror("Send error:"); } /* if(-1 == write(skfd,send_data,strlen(send_data))){ perror("Send error:"); } */ /*客户端只接收服务器发来的数据,然后就退出*/ if(-1 == read(skfd,buf,1024)){ perror("Recv Error:"); } printf("Date arrived:%s",buf); /* 拆除TCP连接 */ close(skfd); sleep(10000); } exit(0); }