栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

基于uloop和usock的TCP客户端断线重连

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基于uloop和usock的TCP客户端断线重连

提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加
例如:第一章 Python 机器学习入门之pandas的使用


提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录
  • 前言
  • 一、具备的基础
  • 二、代码展示
    • 2.测试结果
  • 总结


前言

解决TCP连接过程中意外中断的情况,暂无考虑长时间网络断掉。如果长时间网络断掉,建议起一个定时器来做定时连接


一、具备的基础

你要想看懂这个代码,首先你得了解一下uloop这个框架。网上资料很多,当然这个框架也不是那么完善,有一定的坑在,还是得需要多写写。其次,你得简单了解一下usock,不用那么细致。最后,你有个开发板,或者你装在ubunt上测试。

二、代码展示

代码如下:


#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include "libubox/uloop.h"

#include "tool.h"

#define SERVER_IP "172.16.5.14"
#define SERVER_PORD "8888"

struct uloop_fd c_fd;  		 
struct uloop_timeout c_send; 

char recv_buf[64];           


static int reconnect()
{

	int type = USOCK_TCP | USOCK_NOCLOEXEC | USOCK_IPV4ONLY;
	c_fd.fd = usock(type, SERVER_IP, SERVER_PORD); 
	if (c_fd.fd < 0)
	{
		perror("usock error");
		return -1;
	}
	
	uloop_fd_add(&c_fd, ULOOP_READ);
	uloop_timeout_set(&c_send, 2000); //2s发一次
	
	return 0;
}

int clinet_recv(struct uloop_fd *sock, unsigned int events)
{
	int rev_len;
	rev_len = read(sock->fd, recv_buf, sizeof(recv_buf));
	if (rev_len > 0)
	{
		DEBUG_PRINT("Recv:%s Len:%d n", recv_buf, rev_len);
		memset(recv_buf, 0, sizeof(recv_buf));
		write(sock->fd, "#", 1);
	}
	else
	{
		
		DEBUG_PRINT("Recv  failedn");
		goto error;
	}
	return 0;
error:
	if (sock->fd)
	{
		uloop_fd_delete(sock);
		close(sock->fd);
		sock->fd = -1;
		DEBUG_PRINT("Close client fdn");
		uloop_timeout_cancel(&c_send);
		if (reconnect() < 0)
		{
			DEBUG_PRINT("ERROR: INIT FAILEDn");
		}
		else
		{
			DEBUG_PRINT("ConNECT SUCCESS!!!n");
		}
	}
	return 0;
}

static void c_send_timer(struct uloop_timeout *timer)
{
	int ret;
	DEBUG_PRINT("hellon");
	ret = write(c_fd.fd, "hello", 5);
	if (ret < 0)
	{
		uloop_timeout_cancel(timer);
		DEBUG_PRINT("Cancel send n");
	}
	uloop_timeout_set(&c_send, 2000); //2s发一次
}

static int client_init()
{

	int type = USOCK_TCP | USOCK_NOCLOEXEC | USOCK_IPV4ONLY;
	c_fd.fd = usock(type, SERVER_IP, SERVER_PORD); 

	if (c_fd.fd < 0)
	{
		perror("usock");
		return -1;
	}
	
	c_fd.cb = clinet_recv;
	uloop_fd_add(&c_fd, ULOOP_READ);
	
	c_send.cb = c_send_timer;
	uloop_timeout_set(&c_send, 2000); //2s发一次

	return 0;
}
int main()
{

	uloop_init();
	
	if (client_init() < 0)
	{
		DEBUG_PRINT("ERROR: INIT FAILEDn");
	}
	else
	{
		DEBUG_PRINT("ConNECT SUCCESS!!!n");
	}
	uloop_run();

	close(c_fd.fd);
	uloop_done();
	return 0;
}
2.测试结果

客户端状况:

服务端状况


总结

没有太过细致的去帮大家分析一下,注释都已经写了。大家慢慢看吧。有什么问题也可以提问,我会及时回复。如果写的不好,也可以跟我说。如果代码有帮到你,麻烦点一个赞吧。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/674661.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号