RT-Thread TCP通信 UDP通信
测试环境
开发板:NK-980IOT V1.0
开发环境:RT-Thread studio 2.2.1 + NuWriter v1.18
RT-Thread版本:4.0.5
开发板网络连接到路由,开启路由WIF到有以太网的桥接功能连接到主路由 1、先做个简单的TCP client及UDP测试
#include <rtthread.h>
#include "lwip/sockets.h"
#include <lwip/netdb.h>
#define BUFSZ 1024
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;
/* 接收到的参数小于 3 个 */
if (argc < 3)
{
rt_kprintf("Usage: tcpclient URL PORT
");
rt_kprintf("Like: tcpclient 192.168.12.44 5000
");
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
");
return;
}
/* 创建一个 socket,类型是 SOCKET_STREAM,TCP 类型 */
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
/* 创建 socket 失败 */
rt_kprintf("Socket error
");
/* 释放接收缓冲 */
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!
");
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("
received error,close the socket.
");
/* 释放接收缓冲 */
rt_free(recv_data);
break;
}
else if (bytes_received == 0)
{
/* 打印 recv 函数返回值为 0 的警告信息 */
rt_kprintf("
Received warning,recv function return 0.
");
continue;
}
/* 有接收到数据,把末端清零 */
recv_data[bytes_received] = '