网络常用tips

来源:互联网 发布:ubuntu无法删除文件夹 编辑:程序博客网 时间:2024/06/10 08:12

1 read 

1.1 read =0 peer close, 连接断开

1.2 read <0 non-block 有可能没问题. 当返回errno==EAGAIN || errno==EWOULDBLOCK则没有问题; continue 即可,连接没有断开.

比如对端没有listen,connect fail,等listen了,自动成功.

non-block ,用while (1)  connect 


2 select, poll, epoll 区别

select 轮询,上限1024

poll 轮询,非1024 :

 m_nFDHaveEvent = poll(m_arypollfd, m_nfd, 100);

epoll非轮询

2.1 select采用轮询的方式,每一次内核都要遍历 [0,maxfdp1)这么多个文件描述符,即使只有一个fd=1023;要1023次找到

但是epoll采用的方式不需要轮询。

int epoll_wait(int epfd, struct epoll_event * events, intmaxevents, int timeout);

该函数返回需要处理的事件数目

向select只有1个,返回是1,遍历1次结束,从m_events将这个fd读出.

2.2 

epoll使用一个文件描述符管理多个描述符,将用户关系的文件描述符的事件存放到内核的一个事件表中,这样在用户空间和内核空间的copy只需一次。

epoll_ctl(m_epfd, EPOLL_CTL_ADD, rtpDescriptor, &rtp_ev); 所有的fd都放到了m_epfd中. 所以第一次将m_epfd放入内核后,再新增加了,也是m_epfd的值变化,内核仍然是处理的这个变量.

而poll是每次都使m_arypollfd扩大,m_arypollfd变化了,个数变化了,都要重新copy一次到内核。


epollin,epollout 作用

epollin read;

epollout 写网卡,当有拥塞的时候不写,畅通的时候写


阻塞: block 在read
read>0 data; read =0 close ; read <0 出错
非阻塞
read>0 data; read =0 close; read<0存在一种有数据还没发完。即连接没断开,通过while 轮询在那里等


4 发送大数据

a[1*1024*1024];

while (1)
send (a,...) //大数据1M,要循环发送

因为socket buffer,IO buffer等原因,要循环发送,否则会发生1M数据仅仅发送,接收100多k,其他数据莫名其妙的丢失,可能是被冲掉了

原创粉丝点击