diff --git a/examples/network/tcpsendpacket.c b/examples/network/tcpsendpacket.c index 75134c19a2..47bb562506 100644 --- a/examples/network/tcpsendpacket.c +++ b/examples/network/tcpsendpacket.c @@ -1,7 +1,7 @@ #include -#include /* 为了解析主机名,需要包含netdb.h头文件 */ -#include /* 使用BSD socket,需要包含socket.h头文件 */ +#include /* 涓轰簡瑙f瀽涓绘満鍚嶏紝闇瑕佸寘鍚玭etdb.h澶存枃浠 */ +#include /* 浣跨敤BSD socket锛岄渶瑕佸寘鍚玸ocket.h澶存枃浠 */ void tcp_senddata(const char *url, int port, int length) { @@ -10,45 +10,52 @@ void tcp_senddata(const char *url, int port, int length) struct sockaddr_in server_addr; rt_uint8_t *buffer_ptr; - /* 通过函数入口参数url获得host地址(如果是域名,会做域名解析) */ + /* 閫氳繃鍑芥暟鍏ュ彛鍙傛暟url鑾峰緱host鍦板潃锛堝鏋滄槸鍩熷悕锛屼細鍋氬煙鍚嶈В鏋愶級 */ host = gethostbyname(url); - /* 创建一个socket,类型是SOCKET_STREAM,TCP类型 */ + /* 鍒涘缓涓涓猻ocket锛岀被鍨嬫槸SOCKET_STREAM锛孴CP绫诲瀷 */ if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) { - /* 创建socket失败 */ + /* 鍒涘缓socket澶辫触 */ rt_kprintf("Socket error\n"); return; } - /* 申请内存 */ + /* 鐢宠鍐呭瓨 */ buffer_ptr = rt_malloc(length); - /* 构造发送数据 */ + if(RT_NULL == buffer_ptr) + { + /* 鐢宠鍐呭瓨澶辫触 */ + rt_kprintf("No memory\n"); + return; + } + + /* 鏋勯犲彂閫佹暟鎹 */ for (index = 0; index < length; index ++) buffer_ptr[index] = index & 0xff; timeout = 100; - /* 设置发送超时时间100ms */ + /* 璁剧疆鍙戦佽秴鏃舵椂闂100ms */ setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); - /* 初始化预连接的服务端地址 */ + /* 鍒濆鍖栭杩炴帴鐨勬湇鍔$鍦板潃 */ server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); server_addr.sin_addr = *((struct in_addr *)host->h_addr); rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero)); - /* 连接到服务端 */ + /* 杩炴帴鍒版湇鍔$ */ err = connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)); rt_kprintf("TCP thread connect error code: %d\n", err); while (1) { - /* 发送数据到sock连接 */ + /* 鍙戦佹暟鎹埌sock杩炴帴 */ result = send(sock, buffer_ptr, length, MSG_DONTWAIT); - if (result < 0) //数据发送错误处理 + if (result < 0) //鏁版嵁鍙戦侀敊璇鐞 { rt_kprintf("TCP thread send error: %d\n", result); closesocket(sock); - /* 关闭连接,重新创建连接 */ + /* 鍏抽棴杩炴帴锛岄噸鏂板垱寤鸿繛鎺 */ rt_thread_delay(10); if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) @@ -59,7 +66,7 @@ void tcp_senddata(const char *url, int port, int length) } else if (result == 0) { - /* 打印send函数返回值为0的警告信息 */ + /* 鎵撳嵃send鍑芥暟杩斿洖鍊间负0鐨勮鍛婁俊鎭 */ rt_kprintf("\n Send warning,send function return 0.\r\n"); } } @@ -67,7 +74,7 @@ void tcp_senddata(const char *url, int port, int length) #ifdef RT_USING_FINSH #include -/* 输出tcpclient函数到finsh shell中 */ +/* 杈撳嚭tcpclient鍑芥暟鍒癴insh shell涓 */ FINSH_FUNCTION_EXPORT(tcp_senddata, send a packet through tcp connection); #endif