4.3 TCP客户端通信
本节我们使用开发板建立一个 tcp 客户端,再去连接指定地址和端口的 tcp 服务端并进行数据通信。打开宏定义 DEMO_SOCKET_CLIENT_SERVER、DEMO_CONNECT_NET;
在开发板连网成功后,创建TCP连接。
int demo_socket_client(char *ssid, char *pwd,int port,char *ip)
{
struct tls_ethif * ethif;
c_connect_wifi(ssid,pwd);
while(1)
{
tls_os_time_delay(1);
ethif = tls_netif_get_ethif();
if(ethif->status)
break;
}
socket_client_connect(port,ip);
return 0;
}
创建一个socket连接,连接指定目标的TCP服务器。
static int socket_client_connect(int port, char *ip)
{
int ret;
char sock_rx[DEMO_SOCK_BUF_SIZE] = {0};
struct sockaddr_in pin;
printf("port:%d,ip:%s\n",port,ip);
while(1)
{
memset(&pin, 0, sizeof(struct sockaddr));
pin.sin_family=AF_INET;
pin.sin_addr.s_addr = ipaddr_addr(ip);
pin.sin_port=htons(port);
if((socket_num = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) < 0)
{
printf("creat socket fail, errno:%d\n",errno);
return -1;
}
if (connect(socket_num, (struct sockaddr *)&pin, sizeof(struct sockaddr)) != 0)
{
printf("connect fail errno:%d\n",errno);
}
else
{
printf("connect success\n");
}
while(1)
{
tls_os_time_delay(1000);
ret = send(socket_num, sock_tx, strlen(sock_tx), 0);
if(ret < 0)
{
printf("Error occured during sending, errno:%d\n",errno);
break;
}
ret = recv(socket_num, sock_rx, sizeof(sock_rx)-1, 0);
if(ret < 0)
{
printf("Receive failed, errno:%d\n",errno);
break;
}
else
{
sock_rx[ret] = 0;
printf("\nReceive %d bytes from %s\n",ret,ip);
printf("%s\n",sock_rx);
}
tls_os_time_delay(2);
}
if(socket_num != -1)
{
printf("shutting down socket and restaring...\n");
shutdown(socket_num,0);
closesocket(socket_num);
socket_num = -1;
}
}
}
程序编译并下载到开发板,在 PC 上建立一个 tcp server,设置监听端口为 8080,IP地址为电脑本机的IP。
通过串口指令指定wifi的名称和密码,指定TCP服务器的IP地址和端口号。如:t-client("@snail","ss559550",8080,"192.168.2.103")
连接成功,网络调试助手会收到消息。