EasyManua.ls Logo

Espressif Systems ESP8266EX - ESP-LAUNCHER Development Board

Espressif Systems ESP8266EX
41 pages
Print Icon
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
!
3. Sample Codes
#define󰲧SERVER_IP󰲧󰲧󰲧󰲧󰲧󰲧󰲧󰲧"192.168.1.124"
#define󰲧SERVER_PORT󰲧󰲧󰲧󰲧󰲧󰲧󰲧󰲧1001
3. Implement the TCP communication via socket programming.
Create a socket:
󰲧󰲧󰲧󰲧sta_socket󰲧=󰲧socket(PF_INET,󰲧SOCK_STREAM,󰲧0);
󰲧󰲧󰲧󰲧if󰲧(-1󰲧==󰲧sta_socket)󰲧{
󰲧󰲧󰲧󰲧󰲧󰲧󰲧󰲧close(sta_socket);
󰲧󰲧󰲧󰲧󰲧󰲧󰲧󰲧vTaskDelay(1000󰲧/󰲧portTICK_RATE_MS);
󰲧󰲧󰲧󰲧󰲧󰲧󰲧󰲧printf("ESP8266󰲧TCP󰲧client󰲧task󰲧>󰲧socket󰲧fail!\n");
󰲧󰲧󰲧󰲧󰲧󰲧󰲧󰲧continue;
󰲧󰲧󰲧󰲧}
󰲧󰲧󰲧󰲧printf("ESP8266󰲧TCP󰲧client󰲧task󰲧>󰲧socket󰲧ok!\n");
Create a TCP connection:
󰲧󰲧󰲧󰲧bzero(&remote_ip,󰲧sizeof(struct󰲧sockaddr_in));
󰲧󰲧󰲧󰲧remote_ip.sin_family󰲧=󰲧AF_INET;
󰲧󰲧󰲧󰲧remote_ip.sin_addr.s_addr󰲧=󰲧inet_addr(SERVER_IP);
󰲧󰲧󰲧󰲧remote_ip.sin_port󰲧=󰲧htons(SERVER_PORT);
󰲧󰲧󰲧󰲧if󰲧(0󰲧!=󰲧connect(sta_socket,󰲧(struct󰲧sockaddr󰲧*)(&remote_ip),󰲧sizeof(struct󰲧sockaddr)))󰲧
{
󰲧󰲧󰲧󰲧󰲧󰲧󰲧󰲧close(sta_socket);
󰲧󰲧󰲧󰲧󰲧󰲧󰲧󰲧vTaskDelay(1000󰲧/󰲧portTICK_RATE_MS);
󰲧󰲧󰲧󰲧󰲧󰲧󰲧󰲧printf("ESP8266󰲧TCP󰲧client󰲧task󰲧>󰲧connect󰲧fail!\n");
󰲧󰲧󰲧󰲧󰲧󰲧󰲧󰲧continue;
󰲧󰲧󰲧󰲧}
󰲧󰲧󰲧󰲧printf("ESP8266󰲧TCP󰲧client󰲧task󰲧>󰲧connect󰲧ok!\n");
Send data packets via TCP communication:
󰲧󰲧󰲧󰲧if󰲧(write(sta_socket,󰲧pbuf,󰲧strlen(pbuf)󰲧+󰲧1)󰲧<󰲧0){
󰲧󰲧󰲧󰲧󰲧󰲧󰲧󰲧close(sta_socket);
󰲧󰲧󰲧󰲧󰲧󰲧󰲧󰲧vTaskDelay(1000󰲧/󰲧portTICK_RATE_MS);
󰲧󰲧󰲧󰲧󰲧󰲧󰲧󰲧printf("ESP8266󰲧TCP󰲧client󰲧task󰲧>󰲧send󰲧fail\n");
󰲧󰲧󰲧󰲧󰲧󰲧󰲧󰲧continue;
󰲧󰲧󰲧󰲧}
󰲧󰲧󰲧󰲧printf("ESP8266󰲧TCP󰲧client󰲧task󰲧>󰲧send󰲧success\n");
󰲧󰲧󰲧󰲧free(pbuf);
Receive data packets via TCP communication:
󰲧󰲧󰲧󰲧char󰲧*recv_buf󰲧=󰲧(char󰲧*)zalloc(128);
󰲧󰲧󰲧󰲧while󰲧((recbytes󰲧=󰲧read(sta_socket󰲧,󰲧recv_buf,󰲧128))󰲧>󰲧0)󰲧{
󰲧󰲧󰲧󰲧󰲧󰲧󰲧󰲧recv_buf[recbytes]󰲧=󰲧0;
Espressif
! /!20 37
2017.05

Other manuals for Espressif Systems ESP8266EX

Related product manuals