python socket programming three: long connection, short connection and heartbeat python socket programming three: long connection, meaning short TCP connections and heartbeat heartbeat

python socket programming three: a long connection, short connection, and the heartbeat

Long connections: Open a socket connection, the send and receive the data, the connection is not closed immediately, you can send and receive packets multiple times.

Short connecting: open a socket connection, the send and receive the data, immediately closes the connection.

Heartbeat: when there is no longer connected to the data communication, transmission timing of a packet (heartbeat), to maintain the connection state.

In python, in fact, do not do things so complicated, heartbeat detection will be automatically maintained in the TCP protocol layer, python interface settings only need to call on it, directly on the code:

server side:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#coding=utf-8
__author__  =  '药师Aric'
'''
server端
长连接,短连接,心跳
'''
import  socket
BUF_SIZE  =  1024
host  =  'localhost'
port  =  8083
 
server  =  socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen( 1 #接收的连接数
client, address  =  server.accept()  #因为设置了接收连接数为1,所以不需要放在循环中接收
while  True #循环收发数据包,长连接
     data  =  client.recv(BUF_SIZE)
     print (data.decode())  #python3 要使用decode
     # client.close() #连接不断开,长连接

client side:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#coding=utf-8
__author__  =  '药师Aric'
'''
client端
长连接,短连接,心跳
'''
import  socket
import  time
host  =  'localhost'
port  =  8083
client  =  socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE,  1 #在客户端开启心跳维护
client.connect((host, port))
while  True :
     client.send( 'hello world\r\n' .encode())
     print ( 'send data' )
     time.sleep( 1 #如果想验证长时间没发数据,SOCKET连接会不会断开,则可以设置时间长一点

TCP heartbeat mechanism

Heartbeat mechanism implementation, based on TCP own heartbeat packets, TCP's SO_KEEPALIVE option, the system default default skipping frequency of two hours, after more than two hours, the local TCP implementation will send a packet to the remote Socket. If remote Socket no response is sent back, TCP will continue to try to achieve 11 minutes, until receiving a response. Otherwise it will automatically disconnect Socket connection.

Meaning TCP heartbeat

TCP Novice Mistakes - meaning heartbeat
background
recently interviewed a number of students, found that many novice to use TCP for TCP there are some errors, and these pits also had doubts I had a nice place. Few online article had a detailed analysis of these issues, that is, there is only given directly to the conclusions and practice, no one will clearly explain the ins and outs of them, so I will tell ins and outs of these issues in this series of articles out, hoping that the majority of novice of TCP to avoid these pits.

Question
a question I often ask during the interview is when the TCP ends of A, B to establish a connection, if one end of the network cable unplug or remove the power, then the other end to receive notifications?
The answer is no, but only a few people can correctly answer this question.

The reason
TCP is a connection there is an agreement, but this does not mean that there is an actual connection of a circuit, but a virtual circuit. TCP to establish connections and disconnections are done by sending the data, that is, we often say that the three-way handshake, waving four times. Both ends of the TCP state of preservation of data, on behalf of such a connection, TCP routing device between the two ends only forward the data to the destination, do not know what these data represent actual meaning, did not in which to save any status information that is in the middle of the route connecting the device no concept, just forward the data to the destination, only the sender and the recipient both ends know the real data represents a data transmission connection.

But this illustrates the point, so if you do not send the data can not be disconnected. Under normal circumstances, when the end of the TCP SOCKET A call to the close or end of the process, the operating system sends FIN packets according to the TCP protocol. Will disconnect the terminal B is received. But when there have been exceptions mentioned above: the network cable is unplugged or cut off the power, summed up no opportunity to send off the FIN packets. A routing device and then directly connected though know A device has been disconnected, but the routing device does not save the status of a connection, so it is impossible to inform the routing device A B-side end of the disconnection. The B does not receive a broken data packets will still remain connected. Therefore, the A side or pulled out lines cut off the power supply terminal B can not be notified of the disconnection.

解决方案
保持连接并不是毫无代价的,如果这种异常断开的连接有很多,那么势必会耗费大量的资源,必须要想办法检测出这种异常连接。
检测的方法很简单,只要让B端主动通过这个连接向A端继续发送数据即可。上文说过,A端异常断开后,和A端直接连接的路由器是知道的。当B端发送的数据经过转发后到达这个路由器后,必然最终会返回B端一个目的不可达。此时B端立刻就会知道这条连接其实已经异常断开了。
但是B端不可能知道什么时候会出现这种异常,所以B端必须定时发送数据来检测连接是否异常断开。数据的内容无关紧要,任何数据都能达到这个效果。这个数据就是我们经常在TCP编程中所说的心跳。

KEEP_ALIVE
TCP协议本身就提供了一种这样的机制来探测对端的存活。TCP协议有一个KEEP_LIVE开关,只要打开这个开关就会定时发送一些数据长度为零的探测心跳包,发送的频率和次数都可以设置,具体的方法在网上搜索tcp keepalive即可,网上有很多文章,这里不再赘述。

应用层心跳
除了使用TCP协议本身的保活开关机制,还可以在应用层主动发送心跳数据包,那么在应用层主动发送心跳数据包的方式和TCP协议本身的保活机制有什么区别呢?

应用层的心跳数据包会耗费更多的带宽,因为TCP协议的保活机制发送的是数据长度为零心跳包,而应用层的心跳数据包长度则必然会大于0。
应用层的心跳数据包可以带一些应用所需要的数据,随应用自己控制,而TCP协议的保活机制则是对于应用层透明的,无法利用心跳携带数据。
双向心跳
那么是否只是一端向另一端发送心跳就行了呢?显然不行。因为两端都有可能发生异常断开的情况。所以TCP连接的两端必须都向对端发送心跳。

总结
TCP中不使用心跳通常来说并没有什么问题,但是一旦遇到了连接异常断开,那么就会出现问题。所以任何一个完善的TCP应用都应该使用心跳。
心跳的意义对于很多TCP的初学者而言是个大坑,我写这篇文章希望初学者能够在编写TCP程序时避免这个坑,同时也希望面试者能够深入理解TCP的心跳机制,能够取得更好的面试结果。

test

Guess you like

Origin www.cnblogs.com/leijiangtao/p/11882808.html