Просмотр исходного кода

initial network sample package

luo jiao 7 лет назад
Родитель
Сommit
94b306d593
16 измененных файлов с 2081 добавлено и 2 удалено
  1. 52 0
      .gitignore
  2. 202 0
      LICENSE
  3. 51 2
      README.md
  4. 36 0
      SConscript
  5. 162 0
      httpclient/README.md
  6. 147 0
      httpclient/httpclient.c
  7. 171 0
      tcpclient/README.md
  8. 145 0
      tcpclient/tcpclient.c
  9. 194 0
      tcpclient_select/README.md
  10. 167 0
      tcpclient_select/tcpclient_select.c
  11. 194 0
      tcpserver/README.md
  12. 159 0
      tcpserver/tcpserver.c
  13. 99 0
      udpclient/README.md
  14. 76 0
      udpclient/udpclient.c
  15. 130 0
      udpserver/README.md
  16. 96 0
      udpserver/udpserver.c

+ 52 - 0
.gitignore

@@ -0,0 +1,52 @@
+# Prerequisites
+*.d
+
+# Object files
+*.o
+*.ko
+*.obj
+*.elf
+
+# Linker output
+*.ilk
+*.map
+*.exp
+
+# Precompiled Headers
+*.gch
+*.pch
+
+# Libraries
+*.lib
+*.a
+*.la
+*.lo
+
+# Shared objects (inc. Windows DLLs)
+*.dll
+*.so
+*.so.*
+*.dylib
+
+# Executables
+*.exe
+*.out
+*.app
+*.i*86
+*.x86_64
+*.hex
+
+# Debug files
+*.dSYM/
+*.su
+*.idb
+*.pdb
+
+# Kernel Module Compile Results
+*.mod*
+*.cmd
+.tmp_versions/
+modules.order
+Module.symvers
+Mkfile.old
+dkms.conf

+ 202 - 0
LICENSE

@@ -0,0 +1,202 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "{}"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright {yyyy} {name of copyright owner}
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+

+ 51 - 2
README.md

@@ -1,2 +1,51 @@
-# network-sample
-RT-Thread network samples
+# network samples package
+
+## 1、介绍
+
+这个软件包包含一些网络操作的例程。
+
+### 1.1 目录结构
+
+| 目录             | 例程                            |
+| ---------------- | ------------------------------- |
+| httpclient       | 创建一个 http 客户端             |
+| tcpclient        | 创建一个 TCP 客户端             |
+| tcpserver        | 创建一个 TCP 服务端             |
+| udpclient        | 创建一个 UDP 客户端             |
+| udpserver        | 创建一个 UDP 服务端             |
+| tcpclient_select | 使用 select 接口实现 TCP 客户端 |
+
+### 1.2 许可证
+
+network samples package 遵循 Apache license v2.0 许可,详见 `LICENSE` 文件。
+
+### 1.3 依赖
+
+依赖网络组件。
+
+## 2、如何打开 network samples package
+
+使用 network samples package 需要在 RT-Thread 的包管理器中选择它,具体路径如下:
+
+```
+RT-Thread online packages
+    miscellaneous packages --->
+        samples: kernel and components samples --->
+            a network_samples package for rt-thread --->
+
+```
+
+然后让 RT-Thread 的包管理器自动更新,或者使用 `pkgs --update` 命令更新包到 BSP 中。
+
+## 3、使用 network samples package
+
+在打开 network samples package 后,当进行 BSP 编译时,选择的软件包相关源代码会被加入到 BSP 工程中进行编译。
+
+## 4、注意事项
+
+暂无。
+
+## 5、联系方式 & 感谢
+
+* 维护:name
+* 主页:https://github.com/RT-Thread-packages/network-sample.git

+ 36 - 0
SConscript

@@ -0,0 +1,36 @@
+from building import *
+Import('rtconfig')
+
+src   = []
+cwd   = GetCurrentDir()
+group = []
+CPPPATH = []
+
+# add network samples.
+if GetDepend('NETWORK_SAMPLES_USING_TCP_CLIENT'):
+    src += ['tcpclient/tcpclient.c']
+    CPPPATH += [cwd + '/tcpclient']
+
+if GetDepend('NETWORK_SAMPLES_USING_TCP_SERVER'):
+    src += ['tcpserver/tcpserver.c']
+    CPPPATH += [cwd + '/tcpserver']
+
+if GetDepend('NETWORK_SAMPLES_USING_UDP_CLIENT'):
+    src += ['udpclient/udpclient.c']
+    CPPPATH += [cwd + '/udpclient']
+
+if GetDepend('NETWORK_SAMPLES_USING_UDP_SERVER'):
+    src += ['udpserver/udpserver.c']
+    CPPPATH += [cwd + '/udpserver']
+
+if GetDepend('NETWORK_SAMPLES_USING_TCP_CLIENT_SELECT'):
+    src += ['tcpclient_select/tcpclient_select.c']
+    CPPPATH += [cwd + '/tcpclient_select']
+
+if GetDepend('NETWORK_SAMPLES_USING_HTTP_CLIENT'):
+    src += ['httpclient/httpclient.c']
+    CPPPATH += [cwd + '/httpclient']
+
+group = DefineGroup('network-samples', src, depend = ['PKG_USING_NETWORK_SAMPLES'], CPPPATH = CPPPATH)
+
+Return('group')

+ 162 - 0
httpclient/README.md

@@ -0,0 +1,162 @@
+# 利用 http client 获取天气 #
+
+这个例程展示了如何利用 http client 获取天气,其中我们使用了 webclient 这个工具。
+
+webclient 是一个 **HTTP** 协议的客户端工具 ,我们就是利用这个工具完成与服务器的通信的。
+
+## 程序清单 ##
+
+```{.c}
+/*
+* 程序清单:利用 http client 获取天气
+ *
+ * 这是一个利用 http client 获取天气的例程
+ * 导出 weather 命令到控制终端
+ * 命令调用格式:weather
+ * 无参数
+ * 程序功能:作为一个 http 客户端,通过 GET 方法与远方服务器通信,获取到服务器传来的天气信息
+*/
+
+#include <webclient.h>  /* 使用 HTTP 协议与服务器通信需要包含此头文件 */
+#include <sys/socket.h> /* 使用BSD socket,需要包含socket.h头文件 */
+#include <netdb.h>
+#include <cJSON.h>
+
+#define BUF_SZ       4096        //缓冲区大小
+#define URL_LEN_MAX  256         //网址最大长度
+#define AREA_ID      "101021300" //上海浦东地区 ID
+
+/* 天气数据解析 */
+void weather_data_parse(rt_uint8_t *data)
+{
+    cJSON *root = RT_NULL, *object = RT_NULL, *item = RT_NULL;
+
+    root = cJSON_Parse((const char *)data);
+    if (!root)
+    {
+        rt_kprintf("No memory for cJSON root!\n");
+        return;
+    }
+    object = cJSON_GetObjectItem(root, "sk_info");
+
+    item = cJSON_GetObjectItem(object, "cityName");
+    rt_kprintf("\ncityName:%s ", item->valuestring);
+
+    item = cJSON_GetObjectItem(object, "temp");
+    rt_kprintf("\ntemp    :%s ", item->valuestring);
+
+    item = cJSON_GetObjectItem(object, "wd");
+    rt_kprintf("\nwd      :%s ", item->valuestring);
+
+    item = cJSON_GetObjectItem(object, "ws");
+    rt_kprintf("\nws      :%s ", item->valuestring);
+
+    item = cJSON_GetObjectItem(object, "sd");
+    rt_kprintf("\nsd      :%s ", item->valuestring);
+
+    item = cJSON_GetObjectItem(object, "date");
+    rt_kprintf("\ndate    :%s", item->valuestring);
+
+    item = cJSON_GetObjectItem(object, "time");
+    rt_kprintf("\ntime    :%s \n", item->valuestring);
+
+    if (root != RT_NULL)
+        cJSON_Delete(root);
+}
+void weather(int argc, char **argv)
+{
+    rt_uint8_t *ptr = RT_NULL;
+    int length = 0, result;
+    struct webclient_session *session = RT_NULL;
+    char *weather_url = RT_NULL;
+
+    /* 为 weather_url 分配空间 */
+    weather_url = rt_calloc(1, URL_LEN_MAX);
+    if (!weather_url)
+    {
+        rt_kprintf("No memory for weather_url!\n");
+        goto __exit;
+    }
+    /* 拼接 GET 网址 */
+    rt_snprintf(weather_url, URL_LEN_MAX, "http://mobile.weather.com.cn/data/sk/%s.html", AREA_ID);
+
+    /* 为结构体 webclient_session 分配空间 */
+    session = (struct webclient_session *)rt_calloc(1, sizeof(struct webclient_session));
+    if (!session)
+    {
+        rt_kprintf("No memory for session structure!\n");
+        goto __exit;
+    }
+    
+    /* 连接天气网站 */
+    result = webclient_connect(session, weather_url);
+    if (result < 0)
+    {
+        rt_kprintf("Webclient connect URI(%s) failed!\n", weather_url);
+        goto __exit;
+    }
+    /* 发送官方标准 header */
+    result = webclient_send_header(session, WEBCLIENT_GET, RT_NULL, RT_NULL);
+    if (result < 0)
+    {
+        rt_kprintf("Webclient send header buffer failed return %d!", result);
+        goto __exit;
+    }
+    /* 检查响应 */
+    if (webclient_handle_response(session))
+    {
+        if (session->response != 200)
+        {
+            rt_kprintf("webclient handle response(%d) error!", session->response);
+            goto __exit;
+        }
+    }
+    /* 分配用于存放接收数据的缓冲 */
+    ptr = rt_calloc(1, BUF_SZ);
+    if(!ptr)
+    {
+        rt_kprintf("No memory for data receive buffer!\n");
+        goto __exit;
+    }
+    
+    length = webclient_read(session, ptr, BUF_SZ);
+    ptr[length] = '\0';
+    /* 天气数据解析 */
+    weather_data_parse(ptr);
+
+__exit:
+    /* 释放网址空间 */
+    if (weather_url != RT_NULL)
+        rt_free(weather_url);
+    /* 关闭会话 */
+    if (session != RT_NULL)
+        webclient_close(session);
+    /* 释放缓冲区空间 */
+    if (ptr != RT_NULL)
+        rt_free(ptr);
+}
+
+#ifdef FINSH_USING_MSH
+#include <finsh.h>
+
+MSH_CMD_EXPORT(weather, Get weather by webclient);
+#endif
+```
+
+## 运行结果 ##
+
+```
+cityName:浦东 
+temp    :25℃ 
+wd      :东风 
+ws      :2级 
+sd      :49% 
+date    :20131012
+time    :15:00 
+```
+
+## 程序介绍 ##
+
+在终端调用 weather 即可运行程序。
+
+城市代码参考:https://blog.csdn.net/wanghao940101/article/details/72416518

+ 147 - 0
httpclient/httpclient.c

@@ -0,0 +1,147 @@
+/*
+ * File      : httpclient.c
+ * COPYRIGHT (C) 2006 - 2018, RT-Thread Development Team
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License along
+ *  with this program; if not, write to the Free Software Foundation, Inc.,
+ *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Change Logs:
+ * Date           Author       Notes
+ * 2018-07-20     flybreak     first version
+ */
+
+#include <webclient.h>  /* 使用 HTTP 协议与服务器通信需要包含此头文件 */
+#include <sys/socket.h> /* 使用BSD socket,需要包含socket.h头文件 */
+#include <netdb.h>
+#include <cJSON.h>
+
+#define BUF_SZ       4096        //缓冲区大小
+#define URL_LEN_MAX  256         //网址最大长度
+#define AREA_ID      "101021300" //上海浦东地区 ID
+
+/* 天气数据解析 */
+void weather_data_parse(rt_uint8_t *data)
+{
+    cJSON *root = RT_NULL, *object = RT_NULL, *item = RT_NULL;
+
+    root = cJSON_Parse((const char *)data);
+    if (!root)
+    {
+        rt_kprintf("No memory for cJSON root!\n");
+        return;
+    }
+    object = cJSON_GetObjectItem(root, "sk_info");
+
+    item = cJSON_GetObjectItem(object, "cityName");
+    rt_kprintf("\ncityName:%s ", item->valuestring);
+
+    item = cJSON_GetObjectItem(object, "temp");
+    rt_kprintf("\ntemp    :%s ", item->valuestring);
+
+    item = cJSON_GetObjectItem(object, "wd");
+    rt_kprintf("\nwd      :%s ", item->valuestring);
+
+    item = cJSON_GetObjectItem(object, "ws");
+    rt_kprintf("\nws      :%s ", item->valuestring);
+
+    item = cJSON_GetObjectItem(object, "sd");
+    rt_kprintf("\nsd      :%s ", item->valuestring);
+
+    item = cJSON_GetObjectItem(object, "date");
+    rt_kprintf("\ndate    :%s", item->valuestring);
+
+    item = cJSON_GetObjectItem(object, "time");
+    rt_kprintf("\ntime    :%s \n", item->valuestring);
+
+    if (root != RT_NULL)
+        cJSON_Delete(root);
+}
+void weather(int argc, char **argv)
+{
+    rt_uint8_t *ptr = RT_NULL;
+    int length = 0, result;
+    struct webclient_session *session = RT_NULL;
+    char *weather_url = RT_NULL;
+
+    /* 为 weather_url 分配空间 */
+    weather_url = rt_calloc(1, URL_LEN_MAX);
+    if (!weather_url)
+    {
+        rt_kprintf("No memory for weather_url!\n");
+        goto __exit;
+    }
+    /* 拼接 GET 网址 */
+    rt_snprintf(weather_url, URL_LEN_MAX, "http://mobile.weather.com.cn/data/sk/%s.html", AREA_ID);
+
+    /* 为结构体 webclient_session 分配空间 */
+    session = (struct webclient_session *)rt_calloc(1, sizeof(struct webclient_session));
+    if (!session)
+    {
+        rt_kprintf("No memory for session structure!\n");
+        goto __exit;
+    }
+
+    /* 连接天气网站 */
+    result = webclient_connect(session, weather_url);
+    if (result < 0)
+    {
+        rt_kprintf("Webclient connect URI(%s) failed!\n", weather_url);
+        goto __exit;
+    }
+    /* 发送官方标准 header */
+    result = webclient_send_header(session, WEBCLIENT_GET, RT_NULL, RT_NULL);
+    if (result < 0)
+    {
+        rt_kprintf("Webclient send header buffer failed return %d!", result);
+        goto __exit;
+    }
+    /* 检查响应 */
+    if (webclient_handle_response(session))
+    {
+        if (session->response != 200)
+        {
+            rt_kprintf("webclient handle response(%d) error!", session->response);
+            goto __exit;
+        }
+    }
+    /* 分配用于存放接收数据的缓冲 */
+    ptr = rt_calloc(1, BUF_SZ);
+    if(!ptr)
+    {
+        rt_kprintf("No memory for data receive buffer!\n");
+        goto __exit;
+    }
+
+    length = webclient_read(session, ptr, BUF_SZ);
+    ptr[length] = '\0';
+    /* 天气数据解析 */
+    weather_data_parse(ptr);
+
+__exit:
+    /* 释放网址空间 */
+    if (weather_url != RT_NULL)
+        rt_free(weather_url);
+    /* 关闭会话 */
+    if (session != RT_NULL)
+        webclient_close(session);
+    /* 释放缓冲区空间 */
+    if (ptr != RT_NULL)
+        rt_free(ptr);
+}
+
+#ifdef FINSH_USING_MSH
+#include <finsh.h>
+
+MSH_CMD_EXPORT(weather, Get weather by webclient);
+#endif

+ 171 - 0
tcpclient/README.md

@@ -0,0 +1,171 @@
+# TCP 客户端 #
+
+## 介绍 ##
+
+这个例程展示了如何创建一个 TCP 客户端,跟远端服务器进行通信。
+
+## 程序清单 ##
+
+```{.c}
+/*
+ * 程序清单:tcp 客户端
+ *
+ * 这是一个 tcp 客户端的例程
+ * 导出 tcpclient 命令到控制台 
+ * 命令调用格式:tcpclient URL PORT
+ * URL:服务器地址 PORT::端口号
+ * 程序功能:接收并显示从服务端发送过来的信息,接收到开头是 'q' 或 'Q' 的信息退出程序
+*/
+#include <rtthread.h>
+#include <sys/socket.h> /* 使用BSD socket,需要包含socket.h头文件 */
+#include "netdb.h"
+
+#define BUFSZ   1024
+
+static const char send_data[] = "This is TCP Client from RT-Thread."; /* 发送用到的数据 */
+void tcpclient(int argc, char **argv)
+{
+    int ret;
+    char *recv_data;
+    struct hostent *host;
+    int sock, bytes_received;
+    struct sockaddr_in server_addr;
+    const char *url;
+    int port;
+
+    if (argc < 3)
+    {
+        rt_kprintf("Usage: tcpclient URL PORT\n");
+        rt_kprintf("Like: tcpclient 192.168.12.44 5000\n");
+        return ;
+    }
+
+    url = argv[1];
+    port = strtoul(argv[2], 0, 10);
+
+    /* 通过函数入口参数url获得host地址(如果是域名,会做域名解析) */
+    host = gethostbyname(url);
+
+    /* 分配用于存放接收数据的缓冲 */
+    recv_data = rt_malloc(BUFSZ);
+    if (recv_data == RT_NULL)
+    {
+        rt_kprintf("No memory\n");
+        return;
+    }
+
+    /* 创建一个socket,类型是SOCKET_STREAM,TCP类型 */
+    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+    {
+        /* 创建socket失败 */
+        rt_kprintf("Socket error\n");
+
+        /* 释放接收缓冲 */
+        rt_free(recv_data);
+        return;
+    }
+
+    /* 初始化预连接的服务端地址 */
+    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));
+
+    /* 连接到服务端 */
+    if (connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
+    {
+        /* 连接失败 */
+        rt_kprintf("Connect fail!\n");
+        closesocket(sock);
+
+        /*释放接收缓冲 */
+        rt_free(recv_data);
+        return;
+    }
+
+    while (1)
+    {
+        /* 从sock连接中接收最大BUFSZ - 1字节数据 */
+        bytes_received = recv(sock, recv_data, BUFSZ - 1, 0);
+        if (bytes_received < 0)
+        {
+            /* 接收失败,关闭这个连接 */
+            closesocket(sock);
+            rt_kprintf("\nreceived error,close the socket.\r\n");
+
+            /* 释放接收缓冲 */
+            rt_free(recv_data);
+            break;
+        }
+        else if (bytes_received == 0)
+        {
+            /* 打印recv函数返回值为0的警告信息 */
+            rt_kprintf("\nReceived warning,recv function return 0.\r\n");
+
+            continue;
+        }
+
+        /* 有接收到数据,把末端清零 */
+        recv_data[bytes_received] = '\0';
+
+        if (strncmp(recv_data, "q", 1) == 0 || strncmp(recv_data, "Q", 1) == 0)
+        {
+            /* 如果是首字母是q或Q,关闭这个连接 */
+            closesocket(sock);
+            rt_kprintf("\n got a 'q' or 'Q',close the socket.\r\n");
+
+            /* 释放接收缓冲 */
+            rt_free(recv_data);
+            break;
+        }
+        else
+        {
+            /* 在控制终端显示收到的数据 */
+            rt_kprintf("\nReceived data = %s ", recv_data);
+        }
+
+        /* 发送数据到sock连接 */
+        ret = send(sock, send_data, strlen(send_data), 0);
+        if (ret < 0)
+        {
+            /* 接收失败,关闭这个连接 */
+            closesocket(sock);
+            rt_kprintf("\nsend error,close the socket.\r\n");
+
+            rt_free(recv_data);
+            break;
+        }
+        else if (ret == 0)
+        {
+            /* 打印send函数返回值为0的警告信息 */
+            rt_kprintf("\n Send warning,send function return 0.\r\n");
+        }
+    }
+    return;
+}
+MSH_CMD_EXPORT(tcpclient, a tcp client sample);
+```
+
+## 运行结果 ##
+
+```
+Received data = xxx
+
+Received data = xxx
+
+Received data = xxx
+
+Received data = xxx
+
+Received data = xxx
+...
+got a 'q' or 'Q',close the socket.
+```
+
+## 程序介绍 ##
+
+第一步,需要用网络调试工具在电脑上搭建一个 TCP 客户端,
+
+第二步,在终端调用命令 tcpclient 192.168.xxx.xxx 5000 去连接服务端。
+
+在服务端发送 quit 结束程序运行 。

+ 145 - 0
tcpclient/tcpclient.c

@@ -0,0 +1,145 @@
+/*
+ * 程序清单:tcp 客户端
+ *
+ * 这是一个 tcp 客户端的例程
+ * 导出 tcpclient 命令到控制终端
+ * 命令调用格式:tcpclient URL PORT
+ * URL:服务器地址 PORT::端口号
+ * 程序功能:接收并显示从服务端发送过来的信息,接收到开头是 'q' 或 'Q' 的信息退出程序
+*/
+#include <rtthread.h>
+#include <sys/socket.h> /* 使用BSD socket,需要包含socket.h头文件 */
+#include <netdb.h>
+#include <string.h>
+
+#define BUFSZ   1024
+
+static const char send_data[] = "This is TCP Client from RT-Thread."; /* 发送用到的数据 */
+void tcpclient(int argc, char **argv)
+{
+    int ret;
+    char *recv_data;
+    struct hostent *host;
+    int sock, bytes_received;
+    struct sockaddr_in server_addr;
+    const char *url;
+    int port;
+
+    if (argc < 3)
+    {
+        rt_kprintf("Usage: tcpclient URL PORT\n");
+        rt_kprintf("Like: tcpclient 192.168.12.44 5000\n");
+        return ;
+    }
+
+    url = argv[1];
+    port = strtoul(argv[2], 0, 10);
+
+    /* 通过函数入口参数url获得host地址(如果是域名,会做域名解析) */
+    host = gethostbyname(url);
+
+    /* 分配用于存放接收数据的缓冲 */
+    recv_data = rt_malloc(BUFSZ);
+    if (recv_data == RT_NULL)
+    {
+        rt_kprintf("No memory\n");
+        return;
+    }
+
+    /* 创建一个socket,类型是SOCKET_STREAM,TCP类型 */
+    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+    {
+        /* 创建socket失败 */
+        rt_kprintf("Socket error\n");
+
+        /* 释放接收缓冲 */
+        rt_free(recv_data);
+        return;
+    }
+
+    /* 初始化预连接的服务端地址 */
+    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));
+
+    /* 连接到服务端 */
+    if (connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
+    {
+        /* 连接失败 */
+        rt_kprintf("Connect fail!\n");
+        closesocket(sock);
+
+        /*释放接收缓冲 */
+        rt_free(recv_data);
+        return;
+    }
+
+    while (1)
+    {
+        /* 从sock连接中接收最大BUFSZ - 1字节数据 */
+        bytes_received = recv(sock, recv_data, BUFSZ - 1, 0);
+        if (bytes_received < 0)
+        {
+            /* 接收失败,关闭这个连接 */
+            closesocket(sock);
+            rt_kprintf("\nreceived error,close the socket.\r\n");
+
+            /* 释放接收缓冲 */
+            rt_free(recv_data);
+            break;
+        }
+        else if (bytes_received == 0)
+        {
+            /* 默认 recv 为阻塞模式,此时收到0认为连接出错,关闭这个连接 */
+            closesocket(sock);
+            rt_kprintf("\nreceived error,close the socket.\r\n");
+
+            /* 释放接收缓冲 */
+            rt_free(recv_data);
+            break;
+        }
+
+        /* 有接收到数据,把末端清零 */
+        recv_data[bytes_received] = '\0';
+
+        if (strncmp(recv_data, "q", 1) == 0 || strncmp(recv_data, "Q", 1) == 0)
+        {
+            /* 如果是首字母是q或Q,关闭这个连接 */
+            closesocket(sock);
+            rt_kprintf("\n got a 'q' or 'Q',close the socket.\r\n");
+
+            /* 释放接收缓冲 */
+            rt_free(recv_data);
+            break;
+        }
+        else
+        {
+            /* 在控制终端显示收到的数据 */
+            rt_kprintf("\nReceived data = %s ", recv_data);
+        }
+
+        /* 发送数据到sock连接 */
+        ret = send(sock, send_data, strlen(send_data), 0);
+        if (ret < 0)
+        {
+            /* 接收失败,关闭这个连接 */
+            closesocket(sock);
+            rt_kprintf("\nsend error,close the socket.\r\n");
+
+            rt_free(recv_data);
+            break;
+        }
+        else if (ret == 0)
+        {
+            /* 打印send函数返回值为0的警告信息 */
+            rt_kprintf("\n Send warning,send function return 0.\r\n");
+        }
+    }
+    return;
+}
+#ifdef FINSH_USING_MSH
+#include <finsh.h>
+
+MSH_CMD_EXPORT(tcpclient, a tcp client sample);
+#endif

+ 194 - 0
tcpclient_select/README.md

@@ -0,0 +1,194 @@
+# TCP 客户端 #
+
+## 介绍 ##
+
+这个例程展示了如何使用 DFS NET 提供的 select 接口来创建一个 TCP 客户端,跟远端服务器进行通信。
+
+## 程序清单 ##
+
+```{.c}
+/*
+ * 程序清单:tcp 客户端
+ *
+ * 这是一个 tcp 客户端的例程
+ * 导出 tcpclient 命令到控制终端
+ * 命令调用格式:tcpclient URL PORT
+ * URL:服务器地址 PORT::端口号
+ * 程序功能:接收并显示从服务端发送过来的信息,接收到开头是 'q' 或 'Q' 的信息退出程序
+*/
+#include <rtthread.h>
+#include <sys/socket.h> /* 使用BSD socket,需要包含socket.h头文件 */
+#include "netdb.h"
+#include <sys/select.h> /* 使用 dfs select 功能  */
+
+#define BUFSZ   1024
+
+static const char send_data[] = "This is TCP Client from RT-Thread."; /* 发送用到的数据 */
+void tcpclient_select(int argc, char **argv)
+{
+    int ret;
+    char *recv_data;
+    struct hostent *host;
+    int sock, bytes_received;
+    struct sockaddr_in server_addr;
+    const char *url;
+    int port;
+    fd_set readset;
+    int i, maxfdp1;
+
+    if (argc < 3)
+    {
+        rt_kprintf("Usage: tcpclient URL PORT\n");
+        rt_kprintf("Like: tcpclient 192.168.12.44 5000\n");
+        return ;
+    }
+
+    url = argv[1];
+    port = strtoul(argv[2], 0, 10);
+
+    /* 通过函数入口参数url获得host地址(如果是域名,会做域名解析) */
+    host = gethostbyname(url);
+
+    /* 分配用于存放接收数据的缓冲 */
+    recv_data = rt_malloc(BUFSZ);
+    if (recv_data == RT_NULL)
+    {
+        rt_kprintf("No memory\n");
+        return;
+    }
+
+    /* 创建一个socket,类型是SOCKET_STREAM,TCP类型 */
+    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+    {
+        /* 创建socket失败 */
+        rt_kprintf("Socket error\n");
+
+        /* 释放接收缓冲 */
+        rt_free(recv_data);
+        return;
+    }
+
+    /* 初始化预连接的服务端地址 */
+    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));
+
+    /* 连接到服务端 */
+    if (connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
+    {
+        /* 连接失败 */
+        rt_kprintf("Connect fail!\n");
+        closesocket(sock);
+
+        /*释放接收缓冲 */
+        rt_free(recv_data);
+        return;
+    }
+    
+    /* 获取需要监听的描述符号最大值 */
+    maxfdp1 = sock + 1;
+
+    while (1)
+    {
+        /* 清空可读事件描述符列表 */
+        FD_ZERO(&readset);
+        
+        /* 将需要监听可读事件的描述符加入列表 */
+        FD_SET(sock, &readset);
+
+        /* 等待设定的网络描述符有事件发生 */
+        i = select(maxfdp1, &readset, 0, 0, 0);
+         
+        /* 至少有一个文件描述符有指定事件发生再向后运行 */
+        if (i == 0) continue;
+
+        /* 查看 sock 描述符上有没有发生可读事件 */
+        if (FD_ISSET(sock, &readset))
+        {
+            /* 从sock连接中接收最大BUFSZ - 1字节数据 */
+           bytes_received = recv(sock, recv_data, BUFSZ - 1, 0);
+           if (bytes_received < 0)
+           {
+               /* 接收失败,关闭这个连接 */
+               closesocket(sock);
+               rt_kprintf("\nreceived error,close the socket.\r\n");
+
+               /* 释放接收缓冲 */
+               rt_free(recv_data);
+               break;
+           }
+           else if (bytes_received == 0)
+           {
+               /* 打印recv函数返回值为0的警告信息 */
+               rt_kprintf("\nReceived warning,recv function return 0.\r\n");
+
+               continue;
+           }
+
+           /* 有接收到数据,把末端清零 */
+           recv_data[bytes_received] = '\0';
+
+           if (strncmp(recv_data, "q", 1) == 0 || strncmp(recv_data, "Q", 1) == 0)
+           {
+               /* 如果是首字母是q或Q,关闭这个连接 */
+               closesocket(sock);
+               rt_kprintf("\n got a 'q' or 'Q',close the socket.\r\n");
+
+               /* 释放接收缓冲 */
+               rt_free(recv_data);
+               break;
+           }
+           else
+           {
+               /* 在控制终端显示收到的数据 */
+               rt_kprintf("\nReceived data = %s ", recv_data);
+           }
+
+           /* 发送数据到sock连接 */
+           ret = send(sock, send_data, strlen(send_data), 0);
+           if (ret < 0)
+           {
+               /* 接收失败,关闭这个连接 */
+               closesocket(sock);
+               rt_kprintf("\nsend error,close the socket.\r\n");
+
+               rt_free(recv_data);
+               break;
+           }
+           else if (ret == 0)
+           {
+               /* 打印send函数返回值为0的警告信息 */
+               rt_kprintf("\n Send warning,send function return 0.\r\n");
+           }
+        }
+    }
+    return;
+}
+MSH_CMD_EXPORT(tcpclient_select, a tcp client sample by select api);
+
+```
+
+## 运行结果 ##
+
+```
+Received data = xxx
+
+Received data = xxx
+
+Received data = xxx
+
+Received data = xxx
+
+Received data = xxx
+...
+got a 'q' or 'Q',close the socket.
+```
+
+## 程序介绍 ##
+
+第一步,需要用网络调试工具在电脑上搭建一个 TCP 客户端,
+
+第二步,在终端调用命令 tcpclient 192.168.xxx.xxx 5000 去连接服务端。
+
+在服务端发送 quit 结束程序运行 。

+ 167 - 0
tcpclient_select/tcpclient_select.c

@@ -0,0 +1,167 @@
+/*
+ * 程序清单:tcp 客户端
+ *
+ * 这是一个 tcp 客户端的例程
+ * 导出 tcpclient 命令到控制终端
+ * 命令调用格式:tcpclient URL PORT
+ * URL:服务器地址 PORT::端口号
+ * 程序功能:接收并显示从服务端发送过来的信息,接收到开头是 'q' 或 'Q' 的信息退出程序
+*/
+#include <rtthread.h>
+#include <sys/socket.h> /* 使用BSD socket,需要包含socket.h头文件 */
+#include <netdb.h>
+#include <sys/select.h> /* 使用 dfs select 功能  */
+#include <string.h>
+
+#define BUFSZ   1024
+
+static const char send_data[] = "This is TCP Client from RT-Thread."; /* 发送用到的数据 */
+void tcpclient_select(int argc, char **argv)
+{
+    int ret;
+    char *recv_data;
+    struct hostent *host;
+    int sock, bytes_received;
+    struct sockaddr_in server_addr;
+    const char *url;
+    int port;
+    fd_set readset;
+    int i, maxfdp1;
+
+    if (argc < 3)
+    {
+        rt_kprintf("Usage: tcpclient_select URL PORT\n");
+        rt_kprintf("Like: tcpclient_select 192.168.12.44 5000\n");
+        return ;
+    }
+
+    url = argv[1];
+    port = strtoul(argv[2], 0, 10);
+
+    /* 通过函数入口参数url获得host地址(如果是域名,会做域名解析) */
+    host = gethostbyname(url);
+
+    /* 分配用于存放接收数据的缓冲 */
+    recv_data = rt_malloc(BUFSZ);
+    if (recv_data == RT_NULL)
+    {
+        rt_kprintf("No memory\n");
+        return;
+    }
+
+    /* 创建一个socket,类型是SOCKET_STREAM,TCP类型 */
+    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+    {
+        /* 创建socket失败 */
+        rt_kprintf("Socket error\n");
+
+        /* 释放接收缓冲 */
+        rt_free(recv_data);
+        return;
+    }
+
+    /* 初始化预连接的服务端地址 */
+    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));
+
+    /* 连接到服务端 */
+    if (connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
+    {
+        /* 连接失败 */
+        rt_kprintf("Connect fail!\n");
+        closesocket(sock);
+
+        /*释放接收缓冲 */
+        rt_free(recv_data);
+        return;
+    }
+
+    /* 获取需要监听的描述符号最大值 */
+    maxfdp1 = sock + 1;
+
+    while (1)
+    {
+        /* 清空可读事件描述符列表 */
+        FD_ZERO(&readset);
+
+        /* 将需要监听可读事件的描述符加入列表 */
+        FD_SET(sock, &readset);
+
+        /* 等待设定的网络描述符有事件发生 */
+        i = select(maxfdp1, &readset, 0, 0, 0);
+
+        /* 至少有一个文件描述符有指定事件发生再向后运行 */
+        if (i == 0) continue;
+
+        /* 查看 sock 描述符上有没有发生可读事件 */
+        if (FD_ISSET(sock, &readset))
+        {
+            /* 从sock连接中接收最大BUFSZ - 1字节数据 */
+           bytes_received = recv(sock, recv_data, BUFSZ - 1, 0);
+           if (bytes_received < 0)
+           {
+               /* 接收失败,关闭这个连接 */
+               closesocket(sock);
+               rt_kprintf("\nreceived error,close the socket.\r\n");
+
+               /* 释放接收缓冲 */
+               rt_free(recv_data);
+               break;
+           }
+           else if (bytes_received == 0)
+           {
+               /* 默认 recv 为阻塞模式,此时收到0认为连接出错,关闭这个连接 */
+               closesocket(sock);
+               rt_kprintf("\nreceived error,close the socket.\r\n");
+
+               /* 释放接收缓冲 */
+               rt_free(recv_data);
+               break;
+           }
+
+           /* 有接收到数据,把末端清零 */
+           recv_data[bytes_received] = '\0';
+
+           if (strncmp(recv_data, "q", 1) == 0 || strncmp(recv_data, "Q", 1) == 0)
+           {
+               /* 如果是首字母是q或Q,关闭这个连接 */
+               closesocket(sock);
+               rt_kprintf("\n got a 'q' or 'Q',close the socket.\r\n");
+
+               /* 释放接收缓冲 */
+               rt_free(recv_data);
+               break;
+           }
+           else
+           {
+               /* 在控制终端显示收到的数据 */
+               rt_kprintf("\nReceived data = %s ", recv_data);
+           }
+
+           /* 发送数据到sock连接 */
+           ret = send(sock, send_data, strlen(send_data), 0);
+           if (ret < 0)
+           {
+               /* 接收失败,关闭这个连接 */
+               closesocket(sock);
+               rt_kprintf("\nsend error,close the socket.\r\n");
+
+               rt_free(recv_data);
+               break;
+           }
+           else if (ret == 0)
+           {
+               /* 打印send函数返回值为0的警告信息 */
+               rt_kprintf("\n Send warning,send function return 0.\r\n");
+           }
+        }
+    }
+    return;
+}
+#ifdef FINSH_USING_MSH
+#include <finsh.h>
+
+MSH_CMD_EXPORT(tcpclient_select, a tcp client sample by select api);
+#endif

+ 194 - 0
tcpserver/README.md

@@ -0,0 +1,194 @@
+# TCP 服务端 #
+
+## 介绍 ##
+
+这个例程展示了如何创建一个 TCP 服务端,接受并显示客户端发来的数据。
+
+## 程序清单 ##
+
+```{.c}
+/*
+* 程序清单:tcp 服务端
+ *
+ * 这是一个 tcp 服务端的例程
+ * 导出 tcpserv 命令到控制终端
+ * 命令调用格式:tcpserv
+ * 无参数
+ * 程序功能:作为一个服务端,接收并显示客户端发来的数据 ,接收到 exit 退出程序
+*/
+#include <rtthread.h>
+#include <sys/socket.h> /* 使用BSD socket,需要包含socket.h头文件 */
+#include "netdb.h"
+
+#define BUFSZ       (1024)
+
+static const char send_data[] = "This is TCP Server from RT-Thread."; /* 发送用到的数据 */
+static void tcpserv(int argc, char **argv)
+{
+    char *recv_data; /* 用于接收的指针,后面会做一次动态分配以请求可用内存 */
+    socklen_t sin_size;
+    int sock, connected, bytes_received;
+    struct sockaddr_in server_addr, client_addr;
+    rt_bool_t stop = RT_FALSE; /* 停止标志 */
+    int ret;
+
+    recv_data = rt_malloc(BUFSZ + 1); /* 分配接收用的数据缓冲 */
+    if (recv_data == RT_NULL)
+    {
+        rt_kprintf("No memory\n");
+        return;
+    }
+
+    /* 一个socket在使用前,需要预先创建出来,指定SOCK_STREAM为TCP的socket */
+    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+    {
+        /* 创建失败的错误处理 */
+        rt_kprintf("Socket error\n");
+
+        /* 释放已分配的接收缓冲 */
+        rt_free(recv_data);
+        return;
+    }
+
+    /* 初始化服务端地址 */
+    server_addr.sin_family = AF_INET;
+    server_addr.sin_port = htons(5000); /* 服务端工作的端口 */
+    server_addr.sin_addr.s_addr = INADDR_ANY;
+    rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
+
+    /* 绑定socket到服务端地址 */
+    if (bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
+    {
+        /* 绑定失败 */
+        rt_kprintf("Unable to bind\n");
+
+        /* 释放已分配的接收缓冲 */
+        rt_free(recv_data);
+        return;
+    }
+
+    /* 在socket上进行监听 */
+    if (listen(sock, 5) == -1)
+    {
+        rt_kprintf("Listen error\n");
+
+        /* release recv buffer */
+        rt_free(recv_data);
+        return;
+    }
+
+    rt_kprintf("\nTCPServer Waiting for client on port 5000...\n");
+    while (stop != RT_TRUE)
+    {
+        sin_size = sizeof(struct sockaddr_in);
+
+        /* 接受一个客户端连接socket的请求,这个函数调用是阻塞式的 */
+        connected = accept(sock, (struct sockaddr *)&client_addr, &sin_size);
+        /* 返回的是连接成功的socket */
+        if (connected < 0)
+        {
+            rt_kprintf("accept connection failed! errno = %d\n", errno);
+            continue;
+        }
+
+        /* 接受返回的client_addr指向了客户端的地址信息 */
+        rt_kprintf("I got a connection from (%s , %d)\n",
+                   inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
+
+        /* 客户端连接的处理 */
+        while (1)
+        {
+            /* 发送数据到connected socket */
+            ret = send(connected, send_data, strlen(send_data), 0);
+            if (ret < 0)
+            {
+                /* 发送失败,关闭这个连接 */
+                closesocket(connected);
+                rt_kprintf("\nsend error,close the socket.\r\n");
+                break;
+            }
+            else if (ret == 0)
+            {
+                /* 打印send函数返回值为0的警告信息 */
+                rt_kprintf("\n Send warning,send function return 0.\r\n");
+            }
+
+            /* 从connected socket中接收数据,接收buffer是1024大小,但并不一定能够收到1024大小的数据 */
+            bytes_received = recv(connected, recv_data, BUFSZ, 0);
+            if (bytes_received < 0)
+            {
+                /* 接收失败,关闭这个connected socket */
+                closesocket(connected);
+                break;
+            }
+            else if (bytes_received == 0)
+            {
+                /* 打印recv函数返回值为0的警告信息 */
+                rt_kprintf("\nReceived warning,recv function return 0.\r\n");
+                closesocket(connected);
+                break;
+            }
+
+            /* 有接收到数据,把末端清零 */
+            recv_data[bytes_received] = '\0';
+            if (strcmp(recv_data, "q") == 0 || strcmp(recv_data, "Q") == 0)
+            {
+                /* 如果是首字母是q或Q,关闭这个连接 */
+                closesocket(connected);
+                break;
+            }
+            else if (strcmp(recv_data, "exit") == 0)
+            {
+                /* 如果接收的是exit,则关闭整个服务端 */
+                closesocket(connected);
+                stop = RT_TRUE;
+                break;
+            }
+            else
+            {
+                /* 在控制终端显示收到的数据 */
+                rt_kprintf("RECEIVED DATA = %s \n", recv_data);
+            }
+        }
+    }
+
+    /* 退出服务 */
+    closesocket(sock);
+
+    /* 释放接收缓冲 */
+    rt_free(recv_data);
+
+    return ;
+}
+MSH_CMD_EXPORT(tcpserv, a tcp server sample);
+```
+
+## 运行结果 ##
+
+```
+TCPServer Waiting for client on port 5000...
+I got a connection from (192.168.xx.xx , xxxxx)
+RECEIVED DATA = xxx
+RECEIVED DATA = xxx
+RECEIVED DATA = xxx
+RECEIVED DATA = xxx
+RECEIVED DATA = xxx
+```
+
+## 程序介绍 ##
+
+第一步,在终端调用 ifconfig 查看本机 ip 地址
+
+```
+network interface: e0 (Default)
+MTU: 1500
+MAC: xx xx xx xx xx xx
+FLAGS: UP LINK_UP ETHARP
+ip address: 192.168.12.137
+```
+
+第二步,在终端调用命令 tcpserv 创建一个服务端,端口号为 5000。
+
+第三步,在电脑上用网络调试工具连接开发板,然后就可以发送数据到开发板了
+
+在服务端发送 exit 结束程序运行 。

+ 159 - 0
tcpserver/tcpserver.c

@@ -0,0 +1,159 @@
+/*
+* 程序清单:tcp 服务端
+ *
+ * 这是一个 tcp 服务端的例程
+ * 导出 tcpserv 命令到控制终端
+ * 命令调用格式:tcpserv
+ * 无参数
+ * 程序功能:作为一个服务端,接收并显示客户端发来的数据 ,接收到 exit 退出程序
+*/
+#include <rtthread.h>
+#include <sys/socket.h> /* 使用BSD socket,需要包含socket.h头文件 */
+#include <netdb.h>
+#include <string.h>
+
+#define BUFSZ       (1024)
+
+static const char send_data[] = "This is TCP Server from RT-Thread."; /* 发送用到的数据 */
+static void tcpserv(int argc, char **argv)
+{
+    char *recv_data; /* 用于接收的指针,后面会做一次动态分配以请求可用内存 */
+    socklen_t sin_size;
+    int sock, connected, bytes_received;
+    struct sockaddr_in server_addr, client_addr;
+    rt_bool_t stop = RT_FALSE; /* 停止标志 */
+    int ret;
+
+    recv_data = rt_malloc(BUFSZ + 1); /* 分配接收用的数据缓冲 */
+    if (recv_data == RT_NULL)
+    {
+        rt_kprintf("No memory\n");
+        return;
+    }
+
+    /* 一个socket在使用前,需要预先创建出来,指定SOCK_STREAM为TCP的socket */
+    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+    {
+        /* 创建失败的错误处理 */
+        rt_kprintf("Socket error\n");
+
+        /* 释放已分配的接收缓冲 */
+        rt_free(recv_data);
+        return;
+    }
+
+    /* 初始化服务端地址 */
+    server_addr.sin_family = AF_INET;
+    server_addr.sin_port = htons(5000); /* 服务端工作的端口 */
+    server_addr.sin_addr.s_addr = INADDR_ANY;
+    rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
+
+    /* 绑定socket到服务端地址 */
+    if (bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
+    {
+        /* 绑定失败 */
+        rt_kprintf("Unable to bind\n");
+
+        /* 释放已分配的接收缓冲 */
+        rt_free(recv_data);
+        return;
+    }
+
+    /* 在socket上进行监听 */
+    if (listen(sock, 5) == -1)
+    {
+        rt_kprintf("Listen error\n");
+
+        /* release recv buffer */
+        rt_free(recv_data);
+        return;
+    }
+
+    rt_kprintf("\nTCPServer Waiting for client on port 5000...\n");
+    while (stop != RT_TRUE)
+    {
+        sin_size = sizeof(struct sockaddr_in);
+
+        /* 接受一个客户端连接socket的请求,这个函数调用是阻塞式的 */
+        connected = accept(sock, (struct sockaddr *)&client_addr, &sin_size);
+        /* 返回的是连接成功的socket */
+        if (connected < 0)
+        {
+            rt_kprintf("accept connection failed! errno = %d\n", errno);
+            continue;
+        }
+
+        /* 接受返回的client_addr指向了客户端的地址信息 */
+        rt_kprintf("I got a connection from (%s , %d)\n",
+                   inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
+
+        /* 客户端连接的处理 */
+        while (1)
+        {
+            /* 发送数据到connected socket */
+            ret = send(connected, send_data, strlen(send_data), 0);
+            if (ret < 0)
+            {
+                /* 发送失败,关闭这个连接 */
+                closesocket(connected);
+                rt_kprintf("\nsend error,close the socket.\r\n");
+                break;
+            }
+            else if (ret == 0)
+            {
+                /* 打印send函数返回值为0的警告信息 */
+                rt_kprintf("\n Send warning,send function return 0.\r\n");
+            }
+
+            /* 从connected socket中接收数据,接收buffer是1024大小,但并不一定能够收到1024大小的数据 */
+            bytes_received = recv(connected, recv_data, BUFSZ, 0);
+            if (bytes_received < 0)
+            {
+                /* 接收失败,关闭这个connected socket */
+                closesocket(connected);
+                break;
+            }
+            else if (bytes_received == 0)
+            {
+                /* 打印recv函数返回值为0的警告信息 */
+                rt_kprintf("\nReceived warning,recv function return 0.\r\n");
+                closesocket(connected);
+                break;
+            }
+
+            /* 有接收到数据,把末端清零 */
+            recv_data[bytes_received] = '\0';
+            if (strcmp(recv_data, "q") == 0 || strcmp(recv_data, "Q") == 0)
+            {
+                /* 如果是首字母是q或Q,关闭这个连接 */
+                closesocket(connected);
+                break;
+            }
+            else if (strcmp(recv_data, "exit") == 0)
+            {
+                /* 如果接收的是exit,则关闭整个服务端 */
+                closesocket(connected);
+                stop = RT_TRUE;
+                break;
+            }
+            else
+            {
+                /* 在控制终端显示收到的数据 */
+                rt_kprintf("RECEIVED DATA = %s \n", recv_data);
+            }
+        }
+    }
+
+    /* 退出服务 */
+    closesocket(sock);
+
+    /* 释放接收缓冲 */
+    rt_free(recv_data);
+
+    return ;
+}
+#ifdef FINSH_USING_MSH
+#include <finsh.h>
+
+MSH_CMD_EXPORT(tcpserv, a tcp server sample);
+#endif

+ 99 - 0
udpclient/README.md

@@ -0,0 +1,99 @@
+# UDP 客户端 #
+
+## 介绍 ##
+
+这个例程展示了如何创建一个 UDP 客户端,给远端服务器发送数据。
+
+## 程序清单 ##
+
+```{.c}
+/*
+ * 程序清单:udp 客户端
+ *
+ * 这是一个 udp 客户端的例程
+ * 导出 udpclient 命令到控制终端
+ * 命令调用格式:udpclient URL PORT [COUNT = 10]
+ * URL:服务器地址  PORT:端口号  COUNT:可选参数 默认为 10 
+ * 程序功能:发送 COUNT 条数据到服务远端
+*/
+#include <rtthread.h>
+#include <sys/socket.h> /* 使用BSD socket,需要包含sockets.h头文件 */
+#include "netdb.h"
+
+const char send_data[] = "This is UDP Client from RT-Thread.\n"; /* 发送用到的数据 */
+void udpclient(int argc, char **argv)
+{
+    int sock, port, count;
+    struct hostent *host;
+    struct sockaddr_in server_addr;
+    const char *url;
+
+    if (argc < 3)
+    {
+        rt_kprintf("Usage: udpclient URL PORT [COUNT = 10]\n");
+        rt_kprintf("Like: tcpclient 192.168.12.44 5000\n");
+        return ;
+    }
+
+    url = argv[1];
+    port = strtoul(argv[2], 0, 10);
+
+    if (argc > 3)
+        count = strtoul(argv[3], 0, 10);
+    else
+        count = 10;
+
+    /* 通过函数入口参数url获得host地址(如果是域名,会做域名解析) */
+    host = (struct hostent *) gethostbyname(url);
+
+    /* 创建一个socket,类型是SOCK_DGRAM,UDP类型 */
+    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
+    {
+        rt_kprintf("Socket error\n");
+        return;
+    }
+
+    /* 初始化预连接的服务端地址 */
+    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));
+
+    /* 总计发送count次数据 */
+    while (count)
+    {
+        /* 发送数据到服务远端 */
+        sendto(sock, send_data, strlen(send_data), 0,
+               (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
+
+        /* 线程休眠一段时间 */
+        rt_thread_delay(50);
+
+        /* 计数值减一 */
+        count --;
+    }
+
+    /* 关闭这个socket */
+    closesocket(sock);
+}
+MSH_CMD_EXPORT(udpclient, a udp client sample);
+```
+
+## 运行结果 ##
+
+在电脑上将会接收到以下数据
+
+```
+This is UDP Client from RT-Thread.
+This is UDP Client from RT-Thread.
+This is UDP Client from RT-Thread.
+...
+```
+
+## 程序介绍 ##
+
+第一步,用网络调试工具在电脑上搭建一个 UDP 服务端。
+
+第二步,在开发板上调用命令 tcpclient 192.168.xxx.xxx 5000 给电脑发送几条数据。
+
+发送完数据程序自动结束运行。

+ 76 - 0
udpclient/udpclient.c

@@ -0,0 +1,76 @@
+/*
+ * 程序清单:udp 客户端
+ *
+ * 这是一个 udp 客户端的例程
+ * 导出 udpclient 命令到控制终端
+ * 命令调用格式:udpclient URL PORT [COUNT = 10]
+ * URL:服务器地址  PORT:端口号  COUNT:可选参数 默认为 10 
+ * 程序功能:发送 COUNT 条数据到服务远端
+*/
+#include <rtthread.h>
+#include <sys/socket.h> /* 使用BSD socket,需要包含sockets.h头文件 */
+#include <netdb.h>
+#include <string.h>
+
+const char send_data[] = "This is UDP Client from RT-Thread.\n"; /* 发送用到的数据 */
+void udpclient(int argc, char **argv)
+{
+    int sock, port, count;
+    struct hostent *host;
+    struct sockaddr_in server_addr;
+    const char *url;
+
+    if (argc < 3)
+    {
+        rt_kprintf("Usage: udpclient URL PORT [COUNT = 10]\n");
+        rt_kprintf("Like: tcpclient 192.168.12.44 5000\n");
+        return ;
+    }
+
+    url = argv[1];
+    port = strtoul(argv[2], 0, 10);
+
+    if (argc > 3)
+        count = strtoul(argv[3], 0, 10);
+    else
+        count = 10;
+
+    /* 通过函数入口参数url获得host地址(如果是域名,会做域名解析) */
+    host = (struct hostent *) gethostbyname(url);
+
+    /* 创建一个socket,类型是SOCK_DGRAM,UDP类型 */
+    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
+    {
+        rt_kprintf("Socket error\n");
+        return;
+    }
+
+    /* 初始化预连接的服务端地址 */
+    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));
+
+    /* 总计发送count次数据 */
+    while (count)
+    {
+        /* 发送数据到服务远端 */
+        sendto(sock, send_data, strlen(send_data), 0,
+               (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
+
+        /* 线程休眠一段时间 */
+        rt_thread_delay(50);
+
+        /* 计数值减一 */
+        count --;
+    }
+
+    /* 关闭这个socket */
+    closesocket(sock);
+}
+#ifdef FINSH_USING_MSH
+#include <finsh.h>
+
+MSH_CMD_EXPORT(udpclient, a udp client sample);
+#endif
+

+ 130 - 0
udpserver/README.md

@@ -0,0 +1,130 @@
+# UDP 服务端 #
+
+## 介绍 ##
+
+这个例程展示了如何创建一个 UDP 服务端。
+
+## 程序清单 ##
+
+```{.c}
+/*
+* 程序清单:udp 服务端
+ *
+ * 这是一个 udp 服务端的例程
+ * 导出 udpserv 命令到控制终端
+ * 命令调用格式:udpserv
+ * 无参数
+ * 程序功能:作为一个服务端,接收并显示客户端发来的数据 ,接收到 exit 退出程序
+*/
+#include <rtthread.h>
+#include <sys/socket.h> /* 使用BSD socket,需要包含socket.h头文件 */
+#include "netdb.h"
+
+#define BUFSZ   1024
+
+static void udpserv(int argc, char **argv)
+{
+    int sock;
+    int bytes_read;
+    char *recv_data;
+    socklen_t addr_len;
+    struct sockaddr_in server_addr, client_addr;
+
+    /* 分配接收用的数据缓冲 */
+    recv_data = rt_malloc(BUFSZ);
+    if (recv_data == RT_NULL)
+    {
+        /* 分配内存失败,返回 */
+        rt_kprintf("No memory\n");
+        return;
+    }
+
+    /* 创建一个socket,类型是SOCK_DGRAM,UDP类型 */
+    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
+    {
+        rt_kprintf("Socket error\n");
+
+        /* 释放接收用的数据缓冲 */
+        rt_free(recv_data);
+        return;
+    }
+
+    /* 初始化服务端地址 */
+    server_addr.sin_family = AF_INET;
+    server_addr.sin_port = htons(5000);
+    server_addr.sin_addr.s_addr = INADDR_ANY;
+    rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
+
+    /* 绑定socket到服务端地址 */
+    if (bind(sock, (struct sockaddr *)&server_addr,
+             sizeof(struct sockaddr)) == -1)
+    {
+        /* 绑定地址失败 */
+        rt_kprintf("Bind error\n");
+
+        /* 释放接收用的数据缓冲 */
+        rt_free(recv_data);
+        return;
+    }
+
+    addr_len = sizeof(struct sockaddr);
+    rt_kprintf("UDPServer Waiting for client on port 5000...\n");
+
+    while (1)
+    {
+        /* 从sock中收取最大BUFSZ - 1字节数据 */
+        bytes_read = recvfrom(sock, recv_data, BUFSZ - 1, 0,
+                              (struct sockaddr *)&client_addr, &addr_len);
+        /* UDP不同于TCP,它基本不会出现收取的数据失败的情况,除非设置了超时等待 */
+
+        recv_data[bytes_read] = '\0'; /* 把末端清零 */
+
+        /* 输出接收的数据 */
+        rt_kprintf("\n(%s , %d) said : ", inet_ntoa(client_addr.sin_addr),
+                   ntohs(client_addr.sin_port));
+        rt_kprintf("%s", recv_data);
+
+        /* 如果接收数据是exit,退出 */
+        if (strcmp(recv_data, "exit") == 0)
+        {
+            closesocket(sock);
+
+            /* 释放接收用的数据缓冲 */
+            rt_free(recv_data);
+            break;
+        }
+    }
+
+    return;
+}
+MSH_CMD_EXPORT(udpserv, a udp server sample);
+```
+
+## 运行结果 ##
+
+```
+UDPServer Waiting for client on port 5000...
+
+(192.168.xxx.xxx , xxxxx) said : xxx
+(192.168.xxx.xxx , xxxxx) said : xxx
+(192.168.xxx.xxx , xxxxx) said : xxx
+(192.168.xxx.xxx , xxxxx) said : exit
+```
+
+## 程序介绍 ##
+
+第一步,在终端调用 ifconfig 查看本机 ip 地址
+
+```
+network interface: e0 (Default)
+MTU: 1500
+MAC: xx xx xx xx xx xx
+FLAGS: UP LINK_UP ETHARP
+ip address: 192.168.12.137
+```
+
+第二步,在终端调用命令 udpserv 创建一个 UDP 服务端,端口号为 5000。
+
+第三步,在电脑上用网络调试工具连接开发板,然后就可以发送数据到开发板了
+
+在服务端发送 exit 结束程序运行 。

+ 96 - 0
udpserver/udpserver.c

@@ -0,0 +1,96 @@
+/*
+* 程序清单:udp 服务端
+ *
+ * 这是一个 udp 服务端的例程
+ * 导出 udpserv 命令到控制终端
+ * 命令调用格式:udpserv
+ * 无参数
+ * 程序功能:作为一个服务端,接收并显示客户端发来的数据 ,接收到 exit 退出程序
+*/
+#include <rtthread.h>
+#include <sys/socket.h> /* 使用BSD socket,需要包含socket.h头文件 */
+#include <netdb.h>
+#include <string.h>
+
+#define BUFSZ   1024
+
+static void udpserv(int argc, char **argv)
+{
+    int sock;
+    int bytes_read;
+    char *recv_data;
+    socklen_t addr_len;
+    struct sockaddr_in server_addr, client_addr;
+
+    /* 分配接收用的数据缓冲 */
+    recv_data = rt_malloc(BUFSZ);
+    if (recv_data == RT_NULL)
+    {
+        /* 分配内存失败,返回 */
+        rt_kprintf("No memory\n");
+        return;
+    }
+
+    /* 创建一个socket,类型是SOCK_DGRAM,UDP类型 */
+    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
+    {
+        rt_kprintf("Socket error\n");
+
+        /* 释放接收用的数据缓冲 */
+        rt_free(recv_data);
+        return;
+    }
+
+    /* 初始化服务端地址 */
+    server_addr.sin_family = AF_INET;
+    server_addr.sin_port = htons(5000);
+    server_addr.sin_addr.s_addr = INADDR_ANY;
+    rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
+
+    /* 绑定socket到服务端地址 */
+    if (bind(sock, (struct sockaddr *)&server_addr,
+             sizeof(struct sockaddr)) == -1)
+    {
+        /* 绑定地址失败 */
+        rt_kprintf("Bind error\n");
+
+        /* 释放接收用的数据缓冲 */
+        rt_free(recv_data);
+        return;
+    }
+
+    addr_len = sizeof(struct sockaddr);
+    rt_kprintf("UDPServer Waiting for client on port 5000...\n");
+
+    while (1)
+    {
+        /* 从sock中收取最大BUFSZ - 1字节数据 */
+        bytes_read = recvfrom(sock, recv_data, BUFSZ - 1, 0,
+                              (struct sockaddr *)&client_addr, &addr_len);
+        /* UDP不同于TCP,它基本不会出现收取的数据失败的情况,除非设置了超时等待 */
+
+        recv_data[bytes_read] = '\0'; /* 把末端清零 */
+
+        /* 输出接收的数据 */
+        rt_kprintf("\n(%s , %d) said : ", inet_ntoa(client_addr.sin_addr),
+                   ntohs(client_addr.sin_port));
+        rt_kprintf("%s", recv_data);
+
+        /* 如果接收数据是exit,退出 */
+        if (strcmp(recv_data, "exit") == 0)
+        {
+            closesocket(sock);
+
+            /* 释放接收用的数据缓冲 */
+            rt_free(recv_data);
+            break;
+        }
+    }
+
+    return;
+}
+#ifdef FINSH_USING_MSH
+#include <finsh.h>
+
+MSH_CMD_EXPORT(udpserv, a udp server sample);
+#endif