Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement Protocol TCP persistent connection Framework with socket in python

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "how to use socket to achieve the protocol TCP persistent connection framework in python". The editor shows you the operation process through an actual case, and the operation method is simple, fast and practical. I hope that this article "how to use socket in python to achieve the protocol TCP persistent connection framework" can help you solve the problem.

"use python to implement the TCP persistent connection framework that is common in the protocol."

After analyzing more protocols, we will find that many applications, especially games and IM applications, will use persistent connections to maintain the contact between the client and the server. These persistent connections are usually carried by TCP.

If we want to simulate the behavior of this client, depending on the implementation of different application servers, some persistent connections are not necessary, but some persistent connections must be implemented. For example, a recently analyzed application, although it mainly uses the HTTP protocol for interaction, it transmits some necessary information in the TCP persistent connection. If the persistent connection is not implemented, there will be a lot of information that can not be processed.

In python, it is easy to implement the HTTP protocol, and of course, it is also easy to implement the TCP protocol. Its TCP implementation can use the socket library, but it should be noted that the TCP persistent connection usually transmits hexadecimal data, and the protocol is non-standard, so we need to encapsulate the data format according to the results of protocol analysis.

Here we take a protocol using a persistent connection to TCP as an example to give the TCP persistent connection framework of the protocol. You can refer to the implementation if you need it. Of course, the code is also extracted from the sample and is not complete.

My TCP persistent connection framework, first of all, is the external packaging, initializing some parameters, such as the ip port and socket socket used for the persistent connection.

Self.longip='im.langren001.com' self.longport= 6656 self.threadLock = threading.Lock () self.sockmain = socket.socket (socket.AF_INET, socket.SOCK_STREAM); self.longlinktcpstart2 () tlonglink = threading.Thread (target=lrsuser.longlinktcpth3,name='mainlink_'+ self.playinfo ['uid'], args= (self,)) tlonglink.start () self.threadinfo.append (tlonglink)

In this, two functions are called, one is the longlinktcpstart2 function, which is used to establish the socket connection and realize the interaction when some connections are established initially, and the other is the longlinktcpth3 function, which is a thread to send and receive the data in the connection. Generally speaking, these two can be implemented together, but in order to facilitate the handling of socket exception disconnection, it is divided into two functions.

The implementation of longlinktcpstart2 is as follows:

Def longlinktcpstart2 (self): server_address = (self.longip, int (self.longport)) self.savelogs ('longlinktcpstart2' 'Connecting to% slug% d.'% server_address) self.sockmain.connect (server_address) self.databuf = bounded' message = genbaseinfo.genalive () self.sockmain.sendall (message) message = genbaseinfo.genfirstdata () if len (message) = 0: self.savelogs ('longlinktcpstart2') 'genfirstdata error') return False self.sockmain.sendall (message) self.longlinkcnt=2 cnt= 0 while (cnt)

< 2): try: buf = self.sockmain.recv(2048) sz = len(buf) self.savelogs('longlinktcpstart2', "recv data len "+str(sz) ) if sz >

0: self.databuf + = buf self.dealdatabuf () if cnt = 0: alivemsg = genbaseinfo.genalive () self.sockmain.sendall (alivemsg) self.savelogs ('longlinktcpstart2' "sendalive") regtime=int (round (time.time () * 1000))-random.randint (144000005200000) regtime=regtime*1000 pcode = self.versionstr + '.0' message = genbaseinfo.genseconddata () if len (message) = 0: Self.savelogs ('longlinktcpstart2' 'genseconddata error') return False self.sockmain.sendall (message) self.longlinkcnt = self.longlinkcnt + 1 elif cnt = = 1: pcode = self.versionstr + '.0' message = genbaseinfo.genotherdata () If len (message) = 0: self.savelogs ('longlinktcpstart2' 'genthirddata error') return False self.sockmain.sendall (message) self.longlinkcnt = self.longlinkcnt + 1 cnt = cnt + 1 else: self.savelogs ('longlinktcpstart2' 'recv data alive') except: # socket.error self.savelogs (' longlinktcpstart2', 'socket error,do connect fail') return False return True

The genbaseinfo-related functions can be ignored. They are used to generate the sent message data and can be replaced with their own functions. The dealdatabuf function is used to process the received message data, both of which should be implemented according to the specific protocol analysis. Note that the generated data to be sent and the data received to be processed need to be processed in hexadecimal, which will not be detailed here.

Thread longlinktcpth3 is a loop. The protocol does not exit and the loop does not end. The implementation is as follows:

Def longlinktcpth3 (self): tmalive = 0 R_inputs = set () r_inputs.add (self.sockmain) w_inputs = set () w_inputs.add (self.sockmain) e_inputs = set () e_inputs.add (self.sockmain) tm=int (round (time.time () self.savelogs ('longlinktcpth3' 'enter') while (self.quitflag==0): try: r_list, w_list, e_list = select.select (r_inputs, w_inputs, e_inputs) 1) for event in r_list: try: buf = event.recv (2048) sz = len (buf) self.savelogs ('longlinktcpth3' "loop recv data len:" + str (sz) if sz > 0: self.databuf + = buf self.dealdatabuf () alivemsg = genbaseinfo.genalive () self.sockmain.sendall (alivemsg) Self.savelogs ('longlinktcpth3' "sendalive") else: self.savelogs ('longlinktcpth3', "remote disconnect, do reconnect") r_inputs.clear () time.sleep (3) self.sockmain = socket.socket (socket.AF_INET) Socket.SOCK_STREAM) self.longlinktcpstart2 () r_inputs = set () r_inputs.add (self.sockmain) w_inputs = set () w_inputs.add (self.sockmain) E_inputs = set () e_inputs.add (self.sockmain) except Exception as e: self.savelogs ('longlinktcpth3' Str (e) self.threadLock.acquire () if (len (self.msglist) > 0): msg = self.msglist.pop (0) self.threadLock.release () self.sockmain.sendall (msg) self.savelogs ('longlinktcpth3') "send a msg") else: self.threadLock.release () tmnow=int (round (time.time ()) if tmnow-tm > 30: message = genbaseinfo.genotherdata () if len (message) = 0: self.savelogs ('longlinktcpth3') 'genalivedata error') return False self.sockmain.sendall (message) self.savelogs ('longlinktcpth3', "send alivemsg" + str (self.longlinkcnt)) self.longlinkcnt = self.longlinkcnt + 1 # this needs a unified connection Cannot be confused. Locking tm=tmnow if len (w_list) > 0: # produces a writable event, that is, self.savelogs ('longlinktcpth3',str (w_list)) w_inputs.clear () # when the connection is completed Erase socket if len (e_list) > 0: # generated an error event, that is, a connection error self.savelogs ('longlinktcpth3', str (e_list)) e_inputs.clear () # when a connection error occurs Clear the socket except OSError as e where the error occurred: self.savelogs ('longlinktcpth3',' socket error,do reconnect') time.sleep (3) self.sockmain = socket.socket (socket.AF_INET) Socket.SOCK_STREAM) self.longlinktcpstart2 () r_inputs = set () r_inputs.add (self.sockmain) w_inputs = set () w_inputs.add (self.sockmain) e_inputs = set () e_inputs.add (self.sockmain) Self.savelogs ('longlinktcpth3' 'leave')

Because this code is mainly used on windows, the longlinktcpth3 thread is implemented using select instead of epoll. In the loop, the exception is handled. If an exception occurs and the connection is broken, longlinktcpstart2 is called to reconnect without exiting the loop, and the rest is the same as in longlinktcpstart2.

This is the end of the content about "how to use socket to implement the protocol TCP persistent connection framework in python". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report