예제 #1
0
int main(void)
{
	struct tcp_client *c;
	struct tcp_conf conf = {
		.ipproto	= AF_INET,
		.port		= 1234,
		.client		= {
			.inet_addr	= { inet_addr("127.0.0.1") },
		},
	};
	struct nft_sync_hdr *hdr;
	struct msg_buff *msgb;
	char buf[1024];
	fd_set fds;

	msgb = msgb_alloc(NFTS_MAX_REQUEST);
	if (msgb == NULL) {
		perror("msgb_alloc");
		exit(EXIT_FAILURE);
	}

	hdr = msgb_put(msgb, sizeof(struct nft_sync_hdr) + strlen("fetch"));
	hdr->len = htonl(sizeof(struct nft_sync_hdr) + strlen("fetch"));
	memcpy(hdr->data, "fetch", strlen("fetch"));

	c = tcp_client_create(&conf);
	if (c == NULL) {
		fprintf(stderr, "cannot initialize TCP client\n");
		exit(EXIT_FAILURE);
	}

	FD_ZERO(&fds);
	FD_SET(tcp_client_get_fd(c), &fds);
	/* Wait for connection ... */
	select(tcp_client_get_fd(c) + 1, NULL, &fds, NULL, NULL);

	if (tcp_client_send(c, msgb_data(msgb), msgb_len(msgb)) < 0) {
		perror("cannot send to socket");
		exit(EXIT_FAILURE);
	}

	FD_ZERO(&fds);
	FD_SET(tcp_client_get_fd(c), &fds);
	/* Wait to receive data after sending request ... */
	select(tcp_client_get_fd(c) + 1, &fds, NULL, NULL, NULL);

	if (tcp_client_recv(c, buf, sizeof(buf)) < 0) {
		perror("cannot send to socket");
		exit(EXIT_FAILURE);
	}
	printf("[TEST OK] Received: %s\n", buf + sizeof(struct nft_sync_hdr));
	tcp_client_destroy(c);
}
예제 #2
0
tcp_client_t *tcp_client_create(int max_conn)
{
    tcp_client_t *client = NULL;
    int   max_conn_count = TCP_MAX_STREAM_NUM;
    int                i = 0;

    client = (tcp_client_t *)malloc(sizeof(tcp_client_t));
    if (NULL == client) {
        goto error; 
    }
    bzero(client, sizeof(tcp_client_t));
    client->rcv_cb = rcv_cb_default;
    client->snd_cb = snd_cb_default;

    if (max_conn > 0) {
        max_conn_count = max_conn; 
    }

    /* 创建并发连接结构 */
    client->streams = (tcp_client_stream_t *)malloc(sizeof(tcp_client_stream_t) * max_conn_count);
    if (NULL == client->streams) {
        log_error("malloc for client->streams failed.");
        goto error;
    }
    bzero(client->streams, sizeof(tcp_client_stream_t) * max_conn_count);
    client->stream_num = max_conn_count;

    /* idle stream链表初始化 */
    for (i = 0; i < max_conn_count; i++) {
        client->streams[i].index   = i;
        client->streams[i].sock_fd = -1;
        add_stream_into_idle_list(client, &client->streams[i]); 
    }

    /* 创建epoll句柄 */
    client->epoll_fd = epoll_create(TCP_MAX_CONNECT_NUM);
    if (client->epoll_fd < 0) {
        log_error("epoll_create failed, %s", strerror(errno));
        goto error;
    }
    
    return client;

error:
    tcp_client_destroy(client); 

    return NULL;
}
예제 #3
0
int main(int argc, char **argv) 
{
    pthread_t tid;

    install_signals();

    client = tcp_client_create(10000);
    if (NULL == client) {
        log_error("tcp_client_create failed.");
        return 0;
    }

    pthread_create(&tid, NULL, thr_fn, NULL);

    tcp_client_run(client); 

    tcp_client_destroy(client);

    return 1;
}