网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

dpdkgo语言 dpdk github

C语言等待一定时间输入自动结束?

准备好linux编程环境,现场手撕定时器实现【linux服务器开发】

成都创新互联公司-专业网站定制、快速模板网站建设、高性价比铜梁网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式铜梁网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖铜梁地区。费用合理售后完善,十余年实体公司更值得信赖。

工程师的圣地—Linux内核, 谈谈内核的架构

c/c++ linux服务器开发学习地址:C/C++Linux服务器开发/后台架构师【零声教育】-学习视频教程-腾讯课堂

上图是5个时间轮级联的效果图。中间的大轮是工作轮,只有在它上的任务才会被执行;其他轮上的任务时间到后迁移到下一级轮上,他们最终都会迁移到工作轮上而被调度执行。

多级时间轮的原理也容易理解:就拿时钟做说明,秒针转动一圈分针转动一格;分针转动一圈时针转动一格;同理时间轮也是如此:当低级轮转动一圈时,高一级轮转动一格,同时会将高一级轮上的任务重新分配到低级轮上。从而实现了多级轮级联的效果。

1.1 多级时间轮对象

多级时间轮应该至少包括以下内容:

每一级时间轮对象

轮子上指针的位置

关于轮子上指针的位置有一个比较巧妙的办法:那就是位运算。比如定义一个无符号整型的数:

通过获取当前的系统时间便可以通过位操作转换为时间轮上的时间,通过与实际时间轮上的时间作比较,从而确定时间轮要前进调度的时间,进而操作对应时间轮槽位对应的任务。

为什么至少需要这两个成员呢?

定义多级时间轮,首先需要明确的便是级联的层数,也就是说需要确定有几个时间轮。

轮子上指针位置,就是当前时间轮运行到的位置,它与真实时间的差便是后续时间轮需要调度执行,它们的差值是时间轮运作起来的驱动力。

多级时间轮对象的定义

//实现5级时间轮 范围为0~ (2^8 * 2^6 * 2^6 * 2^6 *2^6)=2^32struct tvec_base{ unsigned long current_index; pthread_t thincrejiffies; pthread_t threadID; struct tvec_root tv1; /*第一个轮*/ struct tvec tv2; /*第二个轮*/ struct tvec tv3; /*第三个轮*/ struct tvec tv4; /*第四个轮*/ struct tvec tv5; /*第五个轮*/};

1.2 时间轮对象

我们知道每一个轮子实际上都是一个哈希表,上面我们只是实例化了五个轮子的对象,但是五个轮子具体包含什么,有几个槽位等等没有明确(即struct tvec和struct tvec_root)。

#define TVN_BITS 6#define TVR_BITS 8#define TVN_SIZE (1

此外,每一个时间轮都是哈希表,因此它的类型应该至少包含两个指针域来实现双向链表的功能。这里我们为了方便使用通用的struct list_head的双向链表结构。

1.3 定时任务对象

定时器的主要工作是为了在未来的特定时间完成某项任务,而这个任务经常包含以下内容:

任务的处理逻辑(回调函数)

任务的参数

双向链表节点

到时时间

定时任务对象的定义

typedef void (*timeouthandle)(unsigned long ); struct timer_list{ struct list_head entry; //将时间连接成链表 unsigned long expires; //超时时间 void (*function)(unsigned long); //超时后的处理函数 unsigned long data; //处理函数的参数 struct tvec_base *base; //指向时间轮};

在时间轮上的效果图:

【文章福利】需要C/C++ Linux服务器架构师学习资料加群812855908(资料包括C/C++,Linux,golang技术,内核,Nginx,ZeroMQ,MySQL,Redis,fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,TCP/IP,协程,DPDK,ffmpeg等)

1.4 双向链表

在时间轮上我们采用双向链表的数据类型。采用双向链表的除了操作上比单链表复杂,多占一个指针域外没有其他不可接收的问题。而多占一个指针域在今天大内存的时代明显不是什么问题。至于双向链表操作的复杂性,我们可以通过使用通用的struct list结构来解决,因为双向链表有众多的标准操作函数,我们可以通过直接引用list.h头文件来使用他们提供的接口。

struct list可以说是一个万能的双向链表操作框架,我们只需要在自定义的结构中定义一个struct list对象即可使用它的标准操作接口。同时它还提供了一个类似container_of的接口,在应用层一般叫做list_entry,因此我们可以很方便的通过struct list成员找到自定义的结构体的起始地址。

关于应用层的log.h, 我将在下面的代码中附上该文件。如果需要内核层的实现,可以直接从linux源码中获取。

1.5 联结方式

多级时间轮效果图:

二. 多级时间轮C语言实现

2.1 双向链表头文件: list.h

提到双向链表,很多的源码工程中都会实现一系列的统一的双向链表操作函数。它们为双向链表封装了统计的接口,使用者只需要在自定义的结构中添加一个struct list_head结构,然后调用它们提供的接口,便可以完成双向链表的所有操作。这些操作一般都在list.h的头文件中实现。Linux源码中也有实现(内核态的实现)。他们实现的方式基本完全一样,只是实现的接口数量和功能上稍有差别。可以说这个list.h文件是学习操作双向链表的不二选择,它几乎实现了所有的操作:增、删、改、查、遍历、替换、清空等等。这里我拼凑了一个源码中的log.h函数,终于凑够了多级时间轮中使用到的接口。

#if !defined(_BLKID_LIST_H) !defined(LIST_HEAD)#define _BLKID_LIST_H#ifdef __cplusplus extern "C" {#endif/* * Simple doubly linked list implementation. * * Some of the internal functions ("__xxx") are useful when * manipulating whole lists rather than single entries, as * sometimes we already know the next/prev entries and we can * generate better code by using them directly rather than * using the generic single-entry routines. */struct list_head { struct list_head *next, *prev;};#define LIST_HEAD_INIT(name) { (name), (name) }#define LIST_HEAD(name) \ struct list_head name = LIST_HEAD_INIT(name)#define INIT_LIST_HEAD(ptr) do { \ (ptr)-next = (ptr); (ptr)-prev = (ptr); \} while (0)static inline void__list_add(struct list_head *entry, struct list_head *prev, struct list_head *next){ next-prev = entry; entry-next = next; entry-prev = prev; prev-next = entry;}/** * Insert a new element after the given list head. The new element does not * need to be initialised as empty list. * The list changes from: * head → some element → ... * to * head → new element → older element → ... * * Example: * struct foo *newfoo = malloc(...); * list_add(newfoo-entry, bar-list_of_foos); * * @param entry The new element to prepend to the list. * @param head The existing list. */static inline voidlist_add(struct list_head *entry, struct list_head *head){ __list_add(entry, head, head-next);}/** * Append a new element to the end of the list given with this list head. * * The list changes from: * head → some element → ... → lastelement * to * head → some element → ... → lastelement → new element * * Example: * struct foo *newfoo = malloc(...); * list_add_tail(newfoo-entry, bar-list_of_foos); * * @param entry The new element to prepend to the list. * @param head The existing list. */static inline voidlist_add_tail(struct list_head *entry, struct list_head *head){ __list_add(entry, head-prev, head);}static inline void__list_del(struct list_head *prev, struct list_head *next){ next-prev = prev; prev-next = next;}/** * Remove the element from the list it is in. Using this function will reset * the pointers to/from this element so it is removed from the list. It does * NOT free the element itself or manipulate it otherwise. * * Using list_del on a pure list head (like in the example at the top of * this file) will NOT remove the first element from * the list but rather reset the list as empty list. * * Example: * list_del(foo-entry); * * @param entry The element to remove. */static inline voidlist_del(struct list_head *entry){ __list_del(entry-prev, entry-next);}static inline voidlist_del_init(struct list_head *entry){ __list_del(entry-prev, entry-next); INIT_LIST_HEAD(entry);}static inline void list_move_tail(struct list_head *list, struct list_head *head){ __list_del(list-prev, list-next); list_add_tail(list, head);}/** * Check if the list is empty. * * Example: * list_empty(bar-list_of_foos); * * @return True if the list contains one or more elements or False otherwise. */static inline intlist_empty(struct list_head *head){ return head-next == head;}/** * list_replace - replace old entry by new one * @old : the element to be replaced * @new : the new element to insert * * If @old was empty, it will be overwritten. */static inline void list_replace(struct list_head *old, struct list_head *new){ new-next = old-next; new-next-prev = new; new-prev = old-prev; new-prev-next = new;}/** * Retrieve the first list entry for the given list pointer. * * Example: * struct foo *first; * first = list_first_entry(bar-list_of_foos, struct foo, list_of_foos); * * @param ptr The list head * @param type Data type of the list element to retrieve * @param member Member name of the struct list_head field in the list element. * @return A pointer to the first list element. */#define list_first_entry(ptr, type, member) \ list_entry((ptr)-next, type, member)static inline void list_replace_init(struct list_head *old, struct list_head *new){ list_replace(old, new); INIT_LIST_HEAD(old);}/** * list_entry - get the struct for this entry * @ptr: the struct list_head pointer. * @type: the type of the struct this is embedded in. * @member: the name of the list_struct within the struct. */#define list_entry(ptr, type, member) \ ((type *)((char *)(ptr)-(unsigned long)(((type *)0)-member)))/** * list_for_each - iterate over elements in a list * @pos: the struct list_head to use as a loop counter. * @head: the head for your list. */#define list_for_each(pos, head) \ for (pos = (head)-next; pos != (head); pos = pos-next)/** * list_for_each_safe - iterate over elements in a list, but don't dereference * pos after the body is done (in case it is freed) * @pos: the struct list_head to use as a loop counter. * @pnext: the struct list_head to use as a pointer to the next item. * @head: the head for your list (not included in iteration). */#define list_for_each_safe(pos, pnext, head) \ for (pos = (head)-next, pnext = pos-next; pos != (head); \ pos = pnext, pnext = pos-next)#ifdef __cplusplus}#endif#endif /* _BLKID_LIST_H */

这里面一般会用到一个重要实现:container_of, 它的原理这里不叙述

2.2 调试信息头文件: log.h

这个头文件实际上不是必须的,我只是用它来添加调试信息(代码中的errlog(), log()都是log.h中的宏函数)。它的效果是给打印的信息加上颜色,效果如下:

log.h的代码如下:

#ifndef _LOG_h_#define _LOG_h_#include #define COL(x) "\033[;" #x "m"#define RED COL(31)#define GREEN COL(32)#define YELLOW COL(33)#define BLUE COL(34)#define MAGENTA COL(35)#define CYAN COL(36)#define WHITE COL(0)#define GRAY "\033[0m"#define errlog(fmt, arg...) do{ \ printf(RED"[#ERROR: Toeny Sun:"GRAY YELLOW" %s:%d]:"GRAY WHITE fmt GRAY, __func__, __LINE__, ##arg);\}while(0)#define log(fmt, arg...) do{ \ printf(WHITE"[#DEBUG: Toeny Sun: "GRAY YELLOW"%s:%d]:"GRAY WHITE fmt GRAY, __func__, __LINE__, ##arg);\}while(0)#endif

2.3 时间轮代码: timewheel.c

/* *毫秒定时器 采用多级时间轮方式 借鉴linux内核中的实现 *支持的范围为1 ~ 2^32 毫秒(大约有49天) *若设置的定时器超过最大值 则按最大值设置定时器 **/#include #include #include #include #include #include #include "list.h"#include "log.h" #define TVN_BITS 6#define TVR_BITS 8#define TVN_SIZE (1current_index (TVR_BITS + (N) * TVN_BITS)) TVN_MASK) typedef void (*timeouthandle)(unsigned long ); struct timer_list{ struct list_head entry; //将时间连接成链表 unsigned long expires; //超时时间 void (*function)(unsigned long); //超时后的处理函数 unsigned long data; //处理函数的参数 struct tvec_base *base; //指向时间轮}; struct tvec { struct list_head vec[TVN_SIZE];}; struct tvec_root{ struct list_head vec[TVR_SIZE];}; //实现5级时间轮 范围为0~ (2^8 * 2^6 * 2^6 * 2^6 *2^6)=2^32struct tvec_base{ unsigned long current_index; pthread_t thincrejiffies; pthread_t threadID; struct tvec_root tv1; /*第一个轮*/ struct tvec tv2; /*第二个轮*/ struct tvec tv3; /*第三个轮*/ struct tvec tv4; /*第四个轮*/ struct tvec tv5; /*第五个轮*/}; static void internal_add_timer(struct tvec_base *base, struct timer_list *timer){ struct list_head *vec; unsigned long expires = timer-expires; unsigned long idx = expires - base-current_index;#if 1 if( (signed long)idx 0 ) /*这里是没有办法区分出是过时还是超长定时的吧?*/ { vec = base-tv1.vec + (base-current_index TVR_MASK);/*放到第一个轮的当前槽*/ } else if ( idx TVR_SIZE ) /*第一个轮*/ { int i = expires TVR_MASK; vec = base-tv1.vec + i; } else if( idx 1 (TVR_BITS + TVN_BITS) )/*第二个轮*/ { int i = (expires TVR_BITS) TVN_MASK; vec = base-tv2.vec + i; } else if( idx 1 (TVR_BITS + 2 * TVN_BITS) )/*第三个轮*/ { int i = (expires (TVR_BITS + TVN_BITS)) TVN_MASK; vec = base-tv3.vec + i; } else if( idx 1 (TVR_BITS + 3 * TVN_BITS) )/*第四个轮*/ { int i = (expires (TVR_BITS + 2 * TVN_BITS)) TVN_MASK; vec = base-tv4.vec + i; } else /*第五个轮*/ { int i; if (idx 0xffffffffUL) { idx = 0xffffffffUL; expires = idx + base-current_index; } i = (expires (TVR_BITS + 3 * TVN_BITS)) TVN_MASK; vec = base-tv5.vec + i; }#else /*上面可以优化吧*/;#endif list_add_tail(timer-entry, vec);} static inline void detach_timer(struct timer_list *timer){ struct list_head *entry = timer-entry; __list_del(entry-prev, entry-next); entry-next = NULL; entry-prev = NULL;} static int __mod_timer(struct timer_list *timer, unsigned long expires){ if(NULL != timer-entry.next) detach_timer(timer); internal_add_timer(timer-base, timer); return 0;} //修改定时器的超时时间外部接口int mod_timer(void *ptimer, unsigned long expires){ struct timer_list *timer = (struct timer_list *)ptimer; struct tvec_base *base; base = timer-base; if(NULL == base) return -1; expires = expires + base-current_index; if(timer-entry.next != NULL timer-expires == expires) return 0; if( NULL == timer-function ) { errlog("timer's timeout function is null\n"); return -1; } timer-expires = expires; return __mod_timer(timer,expires);} //添加一个定时器static void __ti_add_timer(struct timer_list *timer){ if( NULL != timer-entry.next ) { errlog("timer is already exist\n"); return; } mod_timer(timer, timer-expires); } /*添加一个定时器 外部接口 *返回定时器 */void* ti_add_timer(void *ptimewheel, unsigned long expires,timeouthandle phandle, unsigned long arg){ struct timer_list *ptimer; ptimer = (struct timer_list *)malloc( sizeof(struct timer_list) ); if(NULL == ptimer) return NULL; bzero( ptimer,sizeof(struct timer_list) ); ptimer-entry.next = NULL; ptimer-base = (struct tvec_base *)ptimewheel; ptimer-expires = expires; ptimer-function = phandle; ptimer-data = arg; __ti_add_timer(ptimer); return ptimer;} /* *删除一个定时器 外部接口 * * */void ti_del_timer(void *p){ struct timer_list *ptimer =(struct timer_list*)p; if(NULL == ptimer) return; if(NULL != ptimer-entry.next) detach_timer(ptimer); free(ptimer);}/*时间轮级联*/ static int cascade(struct tvec_base *base, struct tvec *tv, int index){ struct list_head *pos,*tmp; struct timer_list *timer; struct list_head tv_list; /*将tv[index]槽位上的所有任务转移给tv_list,然后清空tv[index]*/ list_replace_init(tv-vec + index, tv_list);/*用tv_list替换tv-vec + index*/ list_for_each_safe(pos, tmp, tv_list)/*遍历tv_list双向链表,将任务重新添加到时间轮*/ { timer = list_entry(pos,struct timer_list,entry);/*struct timer_list中成员entry的地址是pos, 获取struct timer_list的首地址*/ internal_add_timer(base, timer); } return index;} static void *deal_function_timeout(void *base){ struct timer_list *timer; int ret; struct timeval tv; struct tvec_base *ba = (struct tvec_base *)base; for(;;) { gettimeofday(tv, NULL); while( ba-current_index = (tv.tv_sec*1000 + tv.tv_usec/1000) )/*单位:ms*/ { struct list_head work_list; int index = ba-current_index TVR_MASK;/*获取第一个轮上的指针位置*/ struct list_head *head = work_list; /*指针指向0槽时,级联轮需要更新任务列表*/ if(!index (!cascade(ba, ba-tv2, INDEX(0))) ( !cascade(ba, ba-tv3, INDEX(1))) (!cascade(ba, ba-tv4, INDEX(2))) ) cascade(ba, ba-tv5, INDEX(3)); ba-current_index ++; list_replace_init(ba-tv1.vec + index, work_list); while(!list_empty(head)) { void (*fn)(unsigned long); unsigned long data; timer = list_first_entry(head, struct timer_list, entry); fn = timer-function; data = timer-data; detach_timer(timer); (*fn)(data); } } }} static void init_tvr_list(struct tvec_root * tvr){ int i; for( i = 0; ivec[i]);} static void init_tvn_list(struct tvec * tvn){ int i; for( i = 0; ivec[i]);} //创建时间轮 外部接口void *ti_timewheel_create(void ){ struct tvec_base *base; int ret = 0; struct timeval tv; base = (struct tvec_base *) malloc( sizeof(struct tvec_base) ); if( NULL==base ) return NULL; bzero( base,sizeof(struct tvec_base) ); init_tvr_list(base-tv1); init_tvn_list(base-tv2); init_tvn_list(base-tv3); init_tvn_list(base-tv4); init_tvn_list(base-tv5); gettimeofday(tv, NULL); base-current_index = tv.tv_sec*1000 + tv.tv_usec/1000;/*当前时间毫秒数*/ if( 0 != pthread_create(base-threadID,NULL,deal_function_timeout,base) ) { free(base); return NULL; } return base;} static void ti_release_tvr(struct tvec_root *pvr){ int i; struct list_head *pos,*tmp; struct timer_list *pen; for(i = 0; i TVR_SIZE; i++) { list_for_each_safe(pos,tmp,pvr-vec[i]) { pen = list_entry(pos,struct timer_list, entry); list_del(pos); free(pen); } }} static void ti_release_tvn(struct tvec *pvn){ int i; struct list_head *pos,*tmp; struct timer_list *pen; for(i = 0; i TVN_SIZE; i++) { list_for_each_safe(pos,tmp,pvn-vec[i]) { pen = list_entry(pos,struct timer_list, entry); list_del(pos); free(pen); } }} /* *释放时间轮 外部接口 * */void ti_timewheel_release(void * pwheel){ struct tvec_base *base = (struct tvec_base *)pwheel; if(NULL == base) return; ti_release_tvr(base-tv1); ti_release_tvn(base-tv2); ti_release_tvn(base-tv3); ti_release_tvn(base-tv4); ti_release_tvn(base-tv5); free(pwheel);} /************demo****************/struct request_para{ void *timer; int val;}; void mytimer(unsigned long arg){ struct request_para *para = (struct request_para *)arg; log("%d\n",para-val); mod_timer(para-timer,3000); //进行再次启动定时器 sleep(10);/*定时器依然被阻塞*/ //定时器资源的释放是在这里完成的 //ti_del_timer(para-timer);} int main(int argc,char *argv[]){ void *pwheel = NULL; void *timer = NULL; struct request_para *para; para = (struct request_para *)malloc( sizeof(struct request_para) ); if(NULL == para) return 0; bzero(para,sizeof(struct request_para)); //创建一个时间轮 pwheel = ti_timewheel_create(); if(NULL == pwheel) return -1; //添加一个定时器 para-val = 100; para-timer = ti_add_timer(pwheel, 3000, mytimer, (unsigned long)para); while(1) { sleep(2); } //释放时间轮 ti_timewheel_release(pwheel); return 0;}

2.4 编译运行

toney@ubantu:/mnt/hgfs/em嵌入式学习记录/4. timerwheel/2. 多级时间轮$ lsa.out list.h log.h mutiTimeWheel.ctoney@ubantu:/mnt/hgfs/em嵌入式学习记录/4. timerwheel/2. 多级时间轮$ gcc mutiTimeWheel.c -lpthreadtoney@ubantu:/mnt/hgfs/em嵌入式学习记录/4. timerwheel/2. 多级时间轮$ ./a.out [#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100

从结果可以看出:如果添加的定时任务是比较耗时的操作,那么后续的任务也会被阻塞,可能一直到超时,甚至一直阻塞下去,这个取决于当前任务是否耗时。这个理论上是绝不能接受的:一个任务不应该也不能去影响其他的任务吧。但是目前没有对此问题进行改进和完善,以后有机会再继续完善吧。

一篇搞懂tcp,http,socket,socket连接池之间的关系

作为一名开发人员我们经常会听到HTTP协议、TCP/IP协议、UDP协议、Socket、Socket长连接、Socket连接池等字眼,然而它们之间的关系、区别及原理并不是所有人都能理解清楚,这篇文章就从网络协议基础开始到Socket连接池,一步一步解释他们之间的关系。

首先从网络通信的分层模型讲起:七层模型,亦称OSI(Open System Interconnection)模型。自下往上分为:物理层、数据链路层、网络层、传输层、会话层、表示层和应用层。所有有关通信的都离不开它,下面这张图片介绍了各层所对应的一些协议和硬件

通过上图,我知道IP协议对应于网络层,TCP、UDP协议对应于传输层,而HTTP协议对应于应用层,OSI并没有Socket,那什么是Socket,后面我们将结合代码具体详细介绍。

关于传输层TCP、UDP协议可能我们平时遇见的会比较多,有人说TCP是安全的,UDP是不安全的,UDP传输比TCP快,那为什么呢,我们先从TCP的连接建立的过程开始分析,然后解释UDP和TCP的区别。

TCP的三次握手和四次分手

我们知道TCP建立连接需要经过三次握手,而断开连接需要经过四次分手,那三次握手和四次分手分别做了什么和如何进行的。

第一次握手: 建立连接。客户端发送连接请求报文段,将SYN位置为1,Sequence Number为x;然后,客户端进入SYN_SEND状态,等待服务器的确认;

第二次握手: 服务器收到客户端的SYN报文段,需要对这个SYN报文段进行确认,设置Acknowledgment Number为x+1(Sequence Number+1);同时,自己自己还要发送SYN请求信息,将SYN位置为1,Sequence Number为y;服务器端将上述所有信息放到一个报文段(即SYN+ACK报文段)中,一并发送给客户端,此时服务器进入SYN_RECV状态;

第三次握手: 客户端收到服务器的SYN+ACK报文段。然后将Acknowledgment Number设置为y+1,向服务器发送ACK报文段,这个报文段发送完毕以后,客户端和服务器端都进入ESTABLISHED状态,完成TCP三次握手。

完成了三次握手,客户端和服务器端就可以开始传送数据。以上就是TCP三次握手的总体介绍。通信结束客户端和服务端就断开连接,需要经过四次分手确认。

第一次分手: 主机1(可以使客户端,也可以是服务器端),设置Sequence Number和Acknowledgment Number,向主机2发送一个FIN报文段;此时,主机1进入FIN_WAIT_1状态;这表示主机1没有数据要发送给主机2了;

第二次分手: 主机2收到了主机1发送的FIN报文段,向主机1回一个ACK报文段,Acknowledgment Number为Sequence Number加1;主机1进入FIN_WAIT_2状态;主机2告诉主机1,我“同意”你的关闭请求;

第三次分手: 主机2向主机1发送FIN报文段,请求关闭连接,同时主机2进入LAST_ACK状态;

第四次分手 :主机1收到主机2发送的FIN报文段,向主机2发送ACK报文段,然后主机1进入TIME_WAIT状态;主机2收到主机1的ACK报文段以后,就关闭连接;此时,主机1等待2MSL后依然没有收到回复,则证明Server端已正常关闭,那好,主机1也可以关闭连接了。

可以看到一次tcp请求的建立及关闭至少进行7次通信,这还不包过数据的通信,而UDP不需3次握手和4次分手。

TCP和UDP的区别

 1、TCP是面向链接的,虽然说网络的不安全不稳定特性决定了多少次握手都不能保证连接的可靠性,但TCP的三次握手在最低限度上(实际上也很大程度上保证了)保证了连接的可靠性;而UDP不是面向连接的,UDP传送数据前并不与对方建立连接,对接收到的数据也不发送确认信号,发送端不知道数据是否会正确接收,当然也不用重发,所以说UDP是无连接的、不可靠的一种数据传输协议。 

 2、也正由于1所说的特点,使得UDP的开销更小数据传输速率更高,因为不必进行收发数据的确认,所以UDP的实时性更好。知道了TCP和UDP的区别,就不难理解为何采用TCP传输协议的MSN比采用UDP的QQ传输文件慢了,但并不能说QQ的通信是不安全的,因为程序员可以手动对UDP的数据收发进行验证,比如发送方对每个数据包进行编号然后由接收方进行验证啊什么的,即使是这样,UDP因为在底层协议的封装上没有采用类似TCP的“三次握手”而实现了TCP所无法达到的传输效率。

关于传输层我们会经常听到一些问题

1.TCP服务器最大并发连接数是多少?

关于TCP服务器最大并发连接数有一种误解就是“因为端口号上限为65535,所以TCP服务器理论上的可承载的最大并发连接数也是65535”。首先需要理解一条TCP连接的组成部分: 客户端IP、客户端端口、服务端IP、服务端端口 。所以对于TCP服务端进程来说,他可以同时连接的客户端数量并不受限于可用端口号,理论上一个服务器的一个端口能建立的连接数是全球的IP数*每台机器的端口数。实际并发连接数受限于linux可打开文件数,这个数是可以配置的,可以非常大,所以实际上受限于系统性能。通过#ulimit -n 查看服务的最大文件句柄数,通过ulimit -n xxx 修改 xxx是你想要能打开的数量。也可以通过修改系统参数:

2.为什么TIME_WAIT状态还需要等2MSL后才能返回到CLOSED状态?

这是因为虽然双方都同意关闭连接了,而且握手的4个报文也都协调和发送完毕,按理可以直接回到CLOSED状态(就好比从SYN_SEND状态到ESTABLISH状态那样);但是因为我们必须要假想网络是不可靠的,你无法保证你最后发送的ACK报文会一定被对方收到,因此对方处于LAST_ACK状态下的Socket可能会因为超时未收到ACK报文,而重发FIN报文,所以这个TIME_WAIT状态的作用就是用来重发可能丢失的ACK报文。

3.TIME_WAIT状态还需要等2MSL后才能返回到CLOSED状态会产生什么问题

通信双方建立TCP连接后,主动关闭连接的一方就会进入TIME_WAIT状态,TIME_WAIT状态维持时间是两个MSL时间长度,也就是在1-4分钟,Windows操作系统就是4分钟。进入TIME_WAIT状态的一般情况下是客户端,一个TIME_WAIT状态的连接就占用了一个本地端口。一台机器上端口号数量的上限是65536个,如果在同一台机器上进行压力测试模拟上万的客户请求,并且循环与服务端进行短连接通信,那么这台机器将产生4000个左右的TIME_WAIT Socket,后续的短连接就会产生address already in use : connect的异常,如果使用Nginx作为方向代理也需要考虑TIME_WAIT状态,发现系统存在大量TIME_WAIT状态的连接,通过调整内核参数解决。

编辑文件,加入以下内容:

然后执行 /sbin/sysctl -p 让参数生效。

net.ipv4.tcp_syncookies = 1 表示开启SYN Cookies。当出现SYN等待队列溢出时,启用cookies来处理,可防范少量SYN攻击,默认为0,表示关闭;

net.ipv4.tcp_tw_reuse = 1 表示开启重用。允许将TIME-WAIT sockets重新用于新的TCP连接,默认为0,表示关闭;

net.ipv4.tcp_tw_recycle = 1 表示开启TCP连接中TIME-WAIT sockets的快速回收,默认为0,表示关闭。

net.ipv4.tcp_fin_timeout 修改系统默认的TIMEOUT时间

相关视频推荐

10道网络八股文,每道都很经典,让你在面试中逼格满满

徒手实现网络协议栈,请准备好环境,一起来写代码

学习地址:C/C++Linux服务器开发/后台架构师【零声教育】-学习视频教程-腾讯课堂

需要C/C++ Linux服务器架构师学习资料加qun812855908获取(资料包括 C/C++,Linux,golang技术,Nginx,ZeroMQ,MySQL,Redis,fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,TCP/IP,协程,DPDK,ffmpeg 等),免费分享

关于TCP/IP和HTTP协议的关系,网络有一段比较容易理解的介绍:“我们在传输数据时,可以只使用(传输层)TCP/IP协议,但是那样的话,如果没有应用层,便无法识别数据内容。如果想要使传输的数据有意义,则必须使用到应用层协议。应用层协议有很多,比如HTTP、FTP、TELNET等,也可以自己定义应用层协议。

HTTP协议即超文本传送协议(Hypertext Transfer Protocol ),是Web联网的基础,也是手机联网常用的协议之一,WEB使用HTTP协议作应用层协议,以封装HTTP文本信息,然后使用TCP/IP做传输层协议将它发到网络上。

由于HTTP在每次请求结束后都会主动释放连接,因此HTTP连接是一种“短连接”,要保持客户端程序的在线状态,需要不断地向服务器发起连接请求。通常 的做法是即时不需要获得任何数据,客户端也保持每隔一段固定的时间向服务器发送一次“保持连接”的请求,服务器在收到该请求后对客户端进行回复,表明知道 客户端“在线”。若服务器长时间无法收到客户端的请求,则认为客户端“下线”,若客户端长时间无法收到服务器的回复,则认为网络已经断开。

下面是一个简单的HTTP Post application/json数据内容的请求:

现在我们了解到TCP/IP只是一个协议栈,就像操作系统的运行机制一样,必须要具体实现,同时还要提供对外的操作接口。就像操作系统会提供标准的编程接口,比如Win32编程接口一样,TCP/IP也必须对外提供编程接口,这就是Socket。现在我们知道,Socket跟TCP/IP并没有必然的联系。Socket编程接口在设计的时候,就希望也能适应其他的网络协议。所以,Socket的出现只是可以更方便的使用TCP/IP协议栈而已,其对TCP/IP进行了抽象,形成了几个最基本的函数接口。比如create,listen,accept,connect,read和write等等。

不同语言都有对应的建立Socket服务端和客户端的库,下面举例Nodejs如何创建服务端和客户端:

服务端:

服务监听9000端口

下面使用命令行发送http请求和telnet

注意到curl只处理了一次报文。

客户端

Socket长连接

所谓长连接,指在一个TCP连接上可以连续发送多个数据包,在TCP连接保持期间,如果没有数据包发送,需要双方发检测包以维持此连接(心跳包),一般需要自己做在线维持。 短连接是指通信双方有数据交互时,就建立一个TCP连接,数据发送完成后,则断开此TCP连接。比如Http的,只是连接、请求、关闭,过程时间较短,服务器若是一段时间内没有收到请求即可关闭连接。其实长连接是相对于通常的短连接而说的,也就是长时间保持客户端与服务端的连接状态。

通常的短连接操作步骤是:

连接 数据传输 关闭连接;

而长连接通常就是:

连接 数据传输 保持连接(心跳) 数据传输 保持连接(心跳) …… 关闭连接;

什么时候用长连接,短连接?

长连接多用于操作频繁,点对点的通讯,而且连接数不能太多情况,。每个TCP连接都需要三步握手,这需要时间,如果每个操作都是先连接,再操作的话那么处理 速度会降低很多,所以每个操作完后都不断开,次处理时直接发送数据包就OK了,不用建立TCP连接。例如:数据库的连接用长连接, 如果用短连接频繁的通信会造成Socket错误,而且频繁的Socket创建也是对资源的浪费。

什么是心跳包为什么需要:

心跳包就是在客户端和服务端间定时通知对方自己状态的一个自己定义的命令字,按照一定的时间间隔发送,类似于心跳,所以叫做心跳包。网络中的接收和发送数据都是使用Socket进行实现。但是如果此套接字已经断开(比如一方断网了),那发送数据和接收数据的时候就一定会有问题。可是如何判断这个套接字是否还可以使用呢?这个就需要在系统中创建心跳机制。其实TCP中已经为我们实现了一个叫做心跳的机制。如果你设置了心跳,那TCP就会在一定的时间(比如你设置的是3秒钟)内发送你设置的次数的心跳(比如说2次),并且此信息不会影响你自己定义的协议。也可以自己定义,所谓“心跳”就是定时发送一个自定义的结构体(心跳包或心跳帧),让对方知道自己“在线”,以确保链接的有效性。

实现:

服务端:

服务端输出结果:

客户端代码:

客户端输出结果:

如果想要使传输的数据有意义,则必须使用到应用层协议比如Http、Mqtt、Dubbo等。基于TCP协议上自定义自己的应用层的协议需要解决的几个问题:

下面我们就一起来定义自己的协议,并编写服务的和客户端进行调用:

定义报文头格式: length:000000000xxxx; xxxx代表数据的长度,总长度20,举例子不严谨。

数据表的格式: Json

服务端:

日志打印:

客户端

日志打印:

客户端定时发送自定义协议数据到服务端,先发送头数据,在发送内容数据,另外一个定时器发送心跳数据,服务端判断是心跳数据,再判断是不是头数据,再是内容数据,然后解析后再发送数据给客户端。从日志的打印可以看出客户端先后writeheader和data数据,服务端可能在一个data事件里面接收到。

这里可以看到一个客户端在同一个时间内处理一个请求可以很好的工作,但是想象这么一个场景,如果同一时间内让同一个客户端去多次调用服务端请求,发送多次头数据和内容数据,服务端的data事件收到的数据就很难区别哪些数据是哪次请求的,比如两次头数据同时到达服务端,服务端就会忽略其中一次,而后面的内容数据也不一定就对应于这个头的。所以想复用长连接并能很好的高并发处理服务端请求,就需要连接池这种方式了。

什么是Socket连接池,池的概念可以联想到是一种资源的集合,所以Socket连接池,就是维护着一定数量Socket长连接的集合。它能自动检测Socket长连接的有效性,剔除无效的连接,补充连接池的长连接的数量。从代码层次上其实是人为实现这种功能的类,一般一个连接池包含下面几个属性:

场景: 一个请求过来,首先去资源池要求获取一个长连接资源,如果空闲队列里面有长连接,就获取到这个长连接Socket,并把这个Socket移到正在运行的长连接队列。如果空闲队列里面没有,且正在运行的队列长度小于配置的连接池资源的数量,就新建一个长连接到正在运行的队列去,如果正在运行的不下于配置的资源池长度,则这个请求进入到等待队列去。当一个正在运行的Socket完成了请求,就从正在运行的队列移到空闲的队列,并触发等待请求队列去获取空闲资源,如果有等待的情况。

这里简单介绍Nodejs的Socket连接池generic-pool模块的源码。

主要文件目录结构

下面介绍库的使用:

初始化连接池

使用连接池

下面连接池的使用,使用的协议是我们之前自定义的协议。

日志打印:

这里看到前面两个请求都建立了新的Socket连接 socket_pool 127.0.0.1 9000 connect,定时器结束后重新发起两个请求就没有建立新的Socket连接了,直接从连接池里面获取Socket连接资源。

源码分析

发现主要的代码就位于lib文件夹中的Pool.js

构造函数:

lib/Pool.js

可以看到包含之前说的空闲的资源队列,正在请求的资源队列,正在等待的请求队列等。

下面查看 Pool.acquire 方法

lib/Pool.js

上面的代码就按种情况一直走下到最终获取到长连接的资源,其他更多代码大家可以自己去深入了解。


本文标题:dpdkgo语言 dpdk github
转载源于:http://bjjierui.cn/article/doeiedo.html

其他资讯