最新消息: USBMI致力于为网友们分享Windows、安卓、IOS等主流手机系统相关的资讯以及评测、同时提供相关教程、应用、软件下载等服务。

为什么心跳包(HeartBeat)是必须的?

互联网 admin 6浏览 0评论

为什么心跳包(HeartBeat)是必须的?

几乎所有的网游服务端都有心跳包(HeartBeat或Ping)的设计,在最近开发手游服务端时,也用到了心跳包。思考思考,心跳包是必须的吗?为什么需要心跳包?TCP没有提供断线检测的方法吗?TCP提供的KeepAlive机制可以替代HeartBeat吗?

由于连接丢失时,TCP不会立即通知应用程序。比如说,客户端程序断线了,服务端的TCP连接不会检测到断线,而是一直处于连接状态。这就带来了很大的麻烦,明明客户端已经断了,服务端还维护着客户端的连接,照常执行着该玩家的游戏逻辑……

心跳包就是用来及时检测是否断线的一种机制,通过每间隔一定时间发送心跳数据,来检测对方是否连接。是属于应用程序协议的一部分。

问题1: TCP为什么不自己提供断线检测?

首先,断线检测需要轮询发送检测报文,会消耗一定的网络带宽和暂用一定的网络资源。如果把它做成TCP的底层默认功能,那些不需要断线检测的应用程序将会浪费不必要的带宽资源。

另外,TCP不提供连接丢失及时通知的最重要原因与其主要设计目的目标之一有关:出现网络故障时维护通信的能力。TCP是美国国防部赞助研究的,一种即使发生战争或自然灾害这种严重网络损坏情况下,也能维护可靠网络通信的网络协议。通常,网络故障只是暂时的,有时路由器会在TCP临时连接丢失后默默的重新连上。所以,TCP本身并不提供那么及时的断线检测。

问题2: TCP的KeepAlive机制可以用来及时检测连接状态吗?

TCP有个KeepAlive开关,打开后可以用来检测死连接。通常默认是2小时,可以自己设置。但是注意,这是TCP的全局设置。假如为了能更及时的检测出断开的连接,把tcp_keepalive_timetcp_keepalive_intvl的时间改小(参考:Link),该机器上所有应用程序的KeepAlive检测间隔都会变小,显然是不能接受的。因为不同应用程序的需求是不一样的。

(在某些平台的Socket实现已经支持为每条连接单独设置KeepAlive参数)

KeepAlive本质上来说,是用来检测长时间不活跃的连接的。所以,不适合用来及时检测连接的状态。

问题3:心跳包(HeartBeat)为什么是好的方式及时检测连接状态?

  1. 具有更大的灵活性,可以自己控制检测的间隔,检测的方式等等。
  2. 心跳包同时适用于TCP和UDP,在切换TCP和UDP时,上层的心跳包功能都适用。(其实这种情况很少遇到)
  3. 有些情况下,心跳包可以附带一些其他信息,定时在服务端和客户端之间同步。(比如帧数同步)

结论

需要及时检测TCP连接状态,心跳包(HeartBeat)还是必须的。


实例:

计算机周期性的发送一个代表心跳的UDP包到服务器,服务器跟踪每台计算机在上次发送心跳之后尽力的时间并报告那些沉默时间太长的计算机。

客户端程序:HeartbeatClient.py

[python]  view plain copy
  1. """ 心跳客户端,周期性的发送 UDP包 """  
  2. import socket, time  
  3. SERVER_IP = '192.168.0.15'; SERVER_PORT = 43278; BEAT_PERIOD = 5  
  4. print 'Sending heartbeat to IP %s , port %d' % (SERVER_IP, SERVER_PORT)  
  5. print 'press Ctrl-C to stop'  
  6. while True:  
  7.     hbSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  
  8.     hbSocket.sendto('PyHB', (SERVER_IP, SERVER_PORT))  
  9.     if _ _debug_ _:  
  10.         print 'Time: %s' % time.ctime( )  
  11.     time.sleep(BEAT_PERIOD)  

服务器程序接受ing跟踪“心跳”,她运行的计算机的地址必须和“客户端”程序中的 SERVER_IP一致。服务器必须支持并发,因为来自不同的计算机的心跳可能会同时到达。一个服务器有两种方法支持并发:多线程和异步操作。下面是一个多线程的ThreadbearServer.py,只使用了Python标准库中的模块:

[python]  view plain copy
  1. """ 多线程 heartbeat 服务器"""  
  2. import socket, threading, time  
  3. UDP_PORT = 43278; CHECK_PERIOD = 20; CHECK_TIMEOUT = 15  
  4. class Heartbeats(dict):  
  5.     """ Manage shared heartbeats dictionary with thread locking """  
  6.     def _ _init_ _(self):  
  7.         super(Heartbeats, self)._ _init_ _( )  
  8.         self._lock = threading.Lock( )  
  9.     def _ _setitem_ _(self, key, value):  
  10.         """ Create or update the dictionary entry for a client """  
  11.         self._lock.acquire( )  
  12.         try:  
  13.             super(Heartbeats, self)._ _setitem_ _(key, value)  
  14.         finally:  
  15.             self._lock.release( )  
  16.     def getSilent(self):  
  17.         """ Return a list of clients with heartbeat older than CHECK_TIMEOUT """  
  18.         limit = time.time( ) - CHECK_TIMEOUT  
  19.         self._lock.acquire( )  
  20.         try:  
  21.             silent = [ip for (ip, ipTime) in self.items( ) if ipTime < limit]  
  22.         finally:  
  23.             self._lock.release( )  
  24.         return silent  
  25. class Receiver(threading.Thread):  
  26.     """ Receive UDP packets and log them in the heartbeats dictionary """  
  27.     def _ _init_ _(self, goOnEvent, heartbeats):  
  28.         super(Receiver, self)._ _init_ _( )  
  29.         self.goOnEvent = goOnEvent  
  30.         self.heartbeats = heartbeats  
  31.         self.recSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  
  32.         self.recSocket.settimeout(CHECK_TIMEOUT)  
  33.         self.recSocket.bind(('', UDP_PORT))  
  34.     def run(self):  
  35.         while self.goOnEvent.isSet( ):  
  36.             try:  
  37.                 data, addr = self.recSocket.recvfrom(5)  
  38.                 if data == 'PyHB':  
  39.                     self.heartbeats[addr[0]] = time.time( )  
  40.             except socket.timeout:  
  41.                 pass  
  42. def main(num_receivers=3):  
  43.     receiverEvent = threading.Event( )  
  44.     receiverEvent.set( )  
  45.     heartbeats = Heartbeats( )  
  46.     receivers = [  ]  
  47.     for i in range(num_receivers):  
  48.         receiver = Receiver(goOnEvent=receiverEvent, heartbeats=heartbeats)  
  49.         receiver.start( )  
  50.         receivers.append(receiver)  
  51.     print 'Threaded heartbeat server listening on port %d' % UDP_PORT  
  52.     print 'press Ctrl-C to stop'  
  53.     try:  
  54.         while True:  
  55.             silent = heartbeats.getSilent( )  
  56.             print 'Silent clients: %s' % silent  
  57.             time.sleep(CHECK_PERIOD)  
  58.     except KeyboardInterrupt:  
  59.         print 'Exiting, please wait...'  
  60.         receiverEvent.clear( )  
  61.         for receiver in receivers:  
  62.             receiver.join( )  
  63.         print 'Finished.'  
  64. if _ _name_ _ == '_ _main_ _':  
  65.     main( )  

NB:在运行该程序时可能出现“ socket.error: [Errno 98] Address already in use”(Linux下) 或 “socket.error: [Errno 10048] 通常每个套接字地址(协议/网络地址/端口)只允许使用一次”(windows下),解决办法参见博文:解决socket.error: [Errno 98] Address already in use问题


作为备选方案,线面给出异步的AsyBeatserver.py程序,这个程序接住了强大的twisted的力量:

[python]  view plain copy
  1. import time  
  2. from twisted.application import internet, service  
  3. from twisted.internet import protocol  
  4. from twisted.python import log  
  5. UDP_PORT = 43278; CHECK_PERIOD = 20; CHECK_TIMEOUT = 15  
  6. class Receiver(protocol.DatagramProtocol):  
  7.     """ Receive UDP packets and log them in the "client"s dictionary """  
  8.     def datagramReceived(self, data, (ip, port)):  
  9.         if data == 'PyHB':  
  10.             self.callback(ip)  
  11. class DetectorService(internet.TimerService):  
  12.     """ Detect clients not sending heartbeats for too long """  
  13.     def _ _init_ _(self):  
  14.         internet.TimerService._ _init_ _(self, CHECK_PERIOD, self.detect)  
  15.         self.beats = {  }  
  16.     def update(self, ip):  
  17.         self.beats[ip] = time.time( )  
  18.     def detect(self):  
  19.         """ Log a list of clients with heartbeat older than CHECK_TIMEOUT """  
  20.         limit = time.time( ) - CHECK_TIMEOUT  
  21.         silent = [ip for (ip, ipTime) in self.beats.items( ) if ipTime < limit]  
  22.         log.msg('Silent clients: %s' % silent)  
  23. application = service.Application('Heartbeat')  
  24. # define and link the silent clients' detector service  
  25. detectorSvc = DetectorService( )  
  26. detectorSvc.setServiceParent(application)  
  27. # create an instance of the Receiver protocol, and give it the callback  
  28. receiver = Receiver( )  
  29. receiver.callback = detectorSvc.update  
  30. # define and link the UDP server service, passing the receiver in  
  31. udpServer = internet.UDPServer(UDP_PORT, receiver)  
  32. udpServer.setServiceParent(application)  
  33. # each service is started automatically by Twisted at launch time  
  34. log.msg('Asynchronous heartbeat server listening on port %d\n'  
  35.     'press Ctrl-C to stop\n' % UDP_PORT)  

为什么心跳包(HeartBeat)是必须的?

几乎所有的网游服务端都有心跳包(HeartBeat或Ping)的设计,在最近开发手游服务端时,也用到了心跳包。思考思考,心跳包是必须的吗?为什么需要心跳包?TCP没有提供断线检测的方法吗?TCP提供的KeepAlive机制可以替代HeartBeat吗?

由于连接丢失时,TCP不会立即通知应用程序。比如说,客户端程序断线了,服务端的TCP连接不会检测到断线,而是一直处于连接状态。这就带来了很大的麻烦,明明客户端已经断了,服务端还维护着客户端的连接,照常执行着该玩家的游戏逻辑……

心跳包就是用来及时检测是否断线的一种机制,通过每间隔一定时间发送心跳数据,来检测对方是否连接。是属于应用程序协议的一部分。

问题1: TCP为什么不自己提供断线检测?

首先,断线检测需要轮询发送检测报文,会消耗一定的网络带宽和暂用一定的网络资源。如果把它做成TCP的底层默认功能,那些不需要断线检测的应用程序将会浪费不必要的带宽资源。

另外,TCP不提供连接丢失及时通知的最重要原因与其主要设计目的目标之一有关:出现网络故障时维护通信的能力。TCP是美国国防部赞助研究的,一种即使发生战争或自然灾害这种严重网络损坏情况下,也能维护可靠网络通信的网络协议。通常,网络故障只是暂时的,有时路由器会在TCP临时连接丢失后默默的重新连上。所以,TCP本身并不提供那么及时的断线检测。

问题2: TCP的KeepAlive机制可以用来及时检测连接状态吗?

TCP有个KeepAlive开关,打开后可以用来检测死连接。通常默认是2小时,可以自己设置。但是注意,这是TCP的全局设置。假如为了能更及时的检测出断开的连接,把tcp_keepalive_timetcp_keepalive_intvl的时间改小(参考:Link),该机器上所有应用程序的KeepAlive检测间隔都会变小,显然是不能接受的。因为不同应用程序的需求是不一样的。

(在某些平台的Socket实现已经支持为每条连接单独设置KeepAlive参数)

KeepAlive本质上来说,是用来检测长时间不活跃的连接的。所以,不适合用来及时检测连接的状态。

问题3:心跳包(HeartBeat)为什么是好的方式及时检测连接状态?

  1. 具有更大的灵活性,可以自己控制检测的间隔,检测的方式等等。
  2. 心跳包同时适用于TCP和UDP,在切换TCP和UDP时,上层的心跳包功能都适用。(其实这种情况很少遇到)
  3. 有些情况下,心跳包可以附带一些其他信息,定时在服务端和客户端之间同步。(比如帧数同步)

结论

需要及时检测TCP连接状态,心跳包(HeartBeat)还是必须的。


实例:

计算机周期性的发送一个代表心跳的UDP包到服务器,服务器跟踪每台计算机在上次发送心跳之后尽力的时间并报告那些沉默时间太长的计算机。

客户端程序:HeartbeatClient.py

[python]  view plain copy
  1. """ 心跳客户端,周期性的发送 UDP包 """  
  2. import socket, time  
  3. SERVER_IP = '192.168.0.15'; SERVER_PORT = 43278; BEAT_PERIOD = 5  
  4. print 'Sending heartbeat to IP %s , port %d' % (SERVER_IP, SERVER_PORT)  
  5. print 'press Ctrl-C to stop'  
  6. while True:  
  7.     hbSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  
  8.     hbSocket.sendto('PyHB', (SERVER_IP, SERVER_PORT))  
  9.     if _ _debug_ _:  
  10.         print 'Time: %s' % time.ctime( )  
  11.     time.sleep(BEAT_PERIOD)  

服务器程序接受ing跟踪“心跳”,她运行的计算机的地址必须和“客户端”程序中的 SERVER_IP一致。服务器必须支持并发,因为来自不同的计算机的心跳可能会同时到达。一个服务器有两种方法支持并发:多线程和异步操作。下面是一个多线程的ThreadbearServer.py,只使用了Python标准库中的模块:

[python]  view plain copy
  1. """ 多线程 heartbeat 服务器"""  
  2. import socket, threading, time  
  3. UDP_PORT = 43278; CHECK_PERIOD = 20; CHECK_TIMEOUT = 15  
  4. class Heartbeats(dict):  
  5.     """ Manage shared heartbeats dictionary with thread locking """  
  6.     def _ _init_ _(self):  
  7.         super(Heartbeats, self)._ _init_ _( )  
  8.         self._lock = threading.Lock( )  
  9.     def _ _setitem_ _(self, key, value):  
  10.         """ Create or update the dictionary entry for a client """  
  11.         self._lock.acquire( )  
  12.         try:  
  13.             super(Heartbeats, self)._ _setitem_ _(key, value)  
  14.         finally:  
  15.             self._lock.release( )  
  16.     def getSilent(self):  
  17.         """ Return a list of clients with heartbeat older than CHECK_TIMEOUT """  
  18.         limit = time.time( ) - CHECK_TIMEOUT  
  19.         self._lock.acquire( )  
  20.         try:  
  21.             silent = [ip for (ip, ipTime) in self.items( ) if ipTime < limit]  
  22.         finally:  
  23.             self._lock.release( )  
  24.         return silent  
  25. class Receiver(threading.Thread):  
  26.     """ Receive UDP packets and log them in the heartbeats dictionary """  
  27.     def _ _init_ _(self, goOnEvent, heartbeats):  
  28.         super(Receiver, self)._ _init_ _( )  
  29.         self.goOnEvent = goOnEvent  
  30.         self.heartbeats = heartbeats  
  31.         self.recSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  
  32.         self.recSocket.settimeout(CHECK_TIMEOUT)  
  33.         self.recSocket.bind(('', UDP_PORT))  
  34.     def run(self):  
  35.         while self.goOnEvent.isSet( ):  
  36.             try:  
  37.                 data, addr = self.recSocket.recvfrom(5)  
  38.                 if data == 'PyHB':  
  39.                     self.heartbeats[addr[0]] = time.time( )  
  40.             except socket.timeout:  
  41.                 pass  
  42. def main(num_receivers=3):  
  43.     receiverEvent = threading.Event( )  
  44.     receiverEvent.set( )  
  45.     heartbeats = Heartbeats( )  
  46.     receivers = [  ]  
  47.     for i in range(num_receivers):  
  48.         receiver = Receiver(goOnEvent=receiverEvent, heartbeats=heartbeats)  
  49.         receiver.start( )  
  50.         receivers.append(receiver)  
  51.     print 'Threaded heartbeat server listening on port %d' % UDP_PORT  
  52.     print 'press Ctrl-C to stop'  
  53.     try:  
  54.         while True:  
  55.             silent = heartbeats.getSilent( )  
  56.             print 'Silent clients: %s' % silent  
  57.             time.sleep(CHECK_PERIOD)  
  58.     except KeyboardInterrupt:  
  59.         print 'Exiting, please wait...'  
  60.         receiverEvent.clear( )  
  61.         for receiver in receivers:  
  62.             receiver.join( )  
  63.         print 'Finished.'  
  64. if _ _name_ _ == '_ _main_ _':  
  65.     main( )  

NB:在运行该程序时可能出现“ socket.error: [Errno 98] Address already in use”(Linux下) 或 “socket.error: [Errno 10048] 通常每个套接字地址(协议/网络地址/端口)只允许使用一次”(windows下),解决办法参见博文:解决socket.error: [Errno 98] Address already in use问题


作为备选方案,线面给出异步的AsyBeatserver.py程序,这个程序接住了强大的twisted的力量:

[python]  view plain copy
  1. import time  
  2. from twisted.application import internet, service  
  3. from twisted.internet import protocol  
  4. from twisted.python import log  
  5. UDP_PORT = 43278; CHECK_PERIOD = 20; CHECK_TIMEOUT = 15  
  6. class Receiver(protocol.DatagramProtocol):  
  7.     """ Receive UDP packets and log them in the "client"s dictionary """  
  8.     def datagramReceived(self, data, (ip, port)):  
  9.         if data == 'PyHB':  
  10.             self.callback(ip)  
  11. class DetectorService(internet.TimerService):  
  12.     """ Detect clients not sending heartbeats for too long """  
  13.     def _ _init_ _(self):  
  14.         internet.TimerService._ _init_ _(self, CHECK_PERIOD, self.detect)  
  15.         self.beats = {  }  
  16.     def update(self, ip):  
  17.         self.beats[ip] = time.time( )  
  18.     def detect(self):  
  19.         """ Log a list of clients with heartbeat older than CHECK_TIMEOUT """  
  20.         limit = time.time( ) - CHECK_TIMEOUT  
  21.         silent = [ip for (ip, ipTime) in self.beats.items( ) if ipTime < limit]  
  22.         log.msg('Silent clients: %s' % silent)  
  23. application = service.Application('Heartbeat')  
  24. # define and link the silent clients' detector service  
  25. detectorSvc = DetectorService( )  
  26. detectorSvc.setServiceParent(application)  
  27. # create an instance of the Receiver protocol, and give it the callback  
  28. receiver = Receiver( )  
  29. receiver.callback = detectorSvc.update  
  30. # define and link the UDP server service, passing the receiver in  
  31. udpServer = internet.UDPServer(UDP_PORT, receiver)  
  32. udpServer.setServiceParent(application)  
  33. # each service is started automatically by Twisted at launch time  
  34. log.msg('Asynchronous heartbeat server listening on port %d\n'  
  35.     'press Ctrl-C to stop\n' % UDP_PORT)  

发布评论

评论列表 (0)

  1. 暂无评论