libuv tcp client

Posted qianbo_insist

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了libuv tcp client相关的知识,希望对你有一定的参考价值。

windows 和 linux 包含

windows下要包含一些lib库,这个需要加进去

#if defined (WIN32) || defined (_WIN32)
#include <WinSock2.h>
#include <windows.h>
#pragma comment(lib,"ws2_32.lib")
#pragma comment(lib,"psapi.lib")
#pragma comment(lib,"Iphlpapi.lib")
#pragma comment(lib,"Userenv.lib")

#else
#include <sys/types.h>
#include <netinet/in.h>
#endif

show me the code

为了和服务器链接测试使用的代码,以下是服务器代码

modbus tcp server 文章

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <uv.h>

#define DEFAULT_IP "127.0.0.1"
#define DEFAULT_PORT 7001

struct sockaddr_in dest;
uv_timer_t*  timer;
uv_loop_t* loop;
uv_write_t write_req;

void write_cb(uv_write_t* req, int status)
{
	if (status < 0) {
		printf("%s\\n", uv_strerror(status));
		return;
	}
	free(req);
}

void timer_cb(uv_timer_t* timer)
{
	uv_buf_t buff = uv_buf_init("hellohappynihaowoshi", 20);

	uv_connect_t* connect = (uv_connect_t*)timer->data;
	uv_stream_t* tcp = connect->handle;

	int buf_count = 1;

	uv_write(&write_req, tcp, &buff, buf_count, write_cb);
}

void on_connect(uv_connect_t* connect, int status)
{
	if (status < 0) {
		printf("connect error: %s!\\n", uv_strerror(status));
		return;
	}
	printf("connect success!");

	timer = (uv_timer_t*)calloc(sizeof(uv_timer_t), 1);
	timer->data = connect;
	uv_timer_init(loop, timer);

	uv_timer_start(timer, timer_cb, 0, 300);

}

typedef struct client_context
{
	uv_loop_t * loop = NULL;
	uv_tcp_t  socket;
	uv_connect_t connect;
	//const char * ip;
	//uint16_t port;
	struct sockaddr_in dest;
	uv_write_t write_req;
}client_context;


int send(uint8_t * data, size_t len)
{
	return 0;
}
void init_client_context(client_context * cc,const char * ip,uint16_t port)
{
	if (cc == NULL)
		return;
	cc->loop = uv_default_loop();
	uv_tcp_init(cc->loop, &cc->socket);
	//cc->ip = ip;
	//cc->port = port;
	uv_ip4_addr(ip, port, &dest);
}

int connect(client_context * cc)
{
	if (cc == NULL)
		return -1;
	int ret = uv_tcp_connect(&cc->connect, &cc->socket, (const struct sockaddr*)&dest, on_connect);
	if (ret) {
		fprintf(stderr, "Connect error: %s\\n", uv_strerror(ret));
		return 0;
	}
	return uv_run(loop, UV_RUN_DEFAULT);

}

int main(int argc, char **argv) {
	loop = uv_default_loop();
	uv_tcp_t  socket;
	uv_tcp_init(loop, &socket);

	uv_connect_t connect;

	uv_ip4_addr(DEFAULT_IP, DEFAULT_PORT, &dest);
	int ret = uv_tcp_connect(&connect, &socket, (const struct sockaddr*)&dest, on_connect);
	if (ret) {
		fprintf(stderr, "Connect error: %s\\n", uv_strerror(ret));
		return 0;
	}
	return uv_run(loop, UV_RUN_DEFAULT);
}

代码比较简单,不做解释,请和服务端配合使用,需要修改端口。

以上是关于libuv tcp client的主要内容,如果未能解决你的问题,请参考以下文章

tcp echo server libuv

libuv 中 sd-bus 的事件循环处理

Nodejs事件引擎libuv源码剖析之:请求(request)结构的设计剖析

fireflyc / million-tcp-client(模拟百万级TCP并发)(代码)

Client / Server Interoperability Support Matrix for Different Oracle Versions (Doc ID 207303.1)(代码片段

异常和TCP通讯