跳转至

TCP客户端

TCP 客户端程序开发流程的介绍

步骤说明:

  1. 创建客户端套接字对象
  2. 和服务端套接字建立连接
  3. 发送数据
  4. 接收数据
  5. 关闭客户端套接字

项目编写

  1. applications/genkipi/app 下新建 tcp_client 文件夹
  2. tcp_client 下新建 main.c 文件
  3. tcp_client 下新建 BUILD.gn文件

代码部分

main.c 文件内容

#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"

#include "genki_wifi_sta.h"

#include "lwip/sockets.h"

#define WIFI_SSID "itheima"
#define WIFI_PASSWORD "12345678"
#define HOSTNAME "itcast"


static void tcp_task(void) {
    wifi_sta_connect(WIFI_SSID, WIFI_PASSWORD, HOSTNAME);

    int sock_fd;
    int ret;
    sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_fd < 0) {
        perror("[actuator_service]sock_fd create error\r\n");
        return;
    }

    // receive addr config
    struct sockaddr_in server_addr;
    socklen_t server_addr_len = sizeof(server_addr);

    memset((void *) &server_addr, 0, server_addr_len);
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr("192.168.31.50");
    server_addr.sin_port = htons(8080);

    ret = connect(sock_fd, (struct sockaddr *) &server_addr, server_addr_len);
    if (ret == -1) {
        perror("connect error\r\n");
        return;
    }

    char *msg = "hello world";
    while (1) {

        ret = send(sock_fd, msg, strlen(msg), 0);

        if (ret == -1) {
            perror("send error\r\n");
            break;
        }

        usleep(1 * 1000 * 1000);
    }
}

static void start(void) {
    osThreadAttr_t attr;

    attr.name = "tcp_client";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024 * 4;
    attr.priority = 25;

    if (osThreadNew((osThreadFunc_t) tcp_task, NULL, &attr) == NULL) {
        printf("Create udp recv task Failed!\r\n");
    }
}

APP_FEATURE_INIT(start);

项目Build.gn

tcp_server 目录下 BUILD.gn 内容为

static_library("tcp_client") {
    sources = [
        "main.c"
    ]

    include_dirs = [
        "//utils/native/lite/include",
        "//base/iot_hardware/peripheral/interfaces/kits",
        "//device/itcast/genkipi/interfaces/kits"
    ]
}

外部Build.gn

tcp_server文件夹上一级目录下BUILD.gn内容为

import("//build/lite/config/component/lite_component.gni")

lite_component("app") {
    features = [
        "tcp_client"
    ]
}