Python Socket Lightweight Server

Source: Internet
Author: User

due to the inherent advantages of python, it is especially useful for fast implementation.

#!/usr/bin/python2.7import sysimport timeimport socket#import modbusimport threadingimport selectclass Thread ( Threading. Thread):d EF __init__ (self,sock): Threading. Thread.__init__ (self) #self. Commond=modbus.modbus () self.sock=sockdef Run (self): Time1=time.time () -10time2= Time.time () try:while true:cr,cw,ce=select.select ([self.sock],[],[self.sock],1) Time2=time.time () if Cr:#//can READSTREAM=SELF.SOCK.RECV (1024x768) if not stream:break#self.commond.parse (stream) if Ce:breakif time2-time1>10:#// 10s Write Once#self.sock.send (self.commond.get_all_data_by_address (0x01)) Time1=time.time () except Exception as Error :p rint (Error) Finally:self.sock.close () print (' Connect closed ') if __name__== ' __main__ ': sock=socket.socket (socket. Af_inet,socket. Sock_stream) Sock.bind ((' 127.0.0.1 ', 8000)) Sock.listen (0) thread_list=list () try:while true:s,ip=sock.accept () print (' New connect:%s:%d '% (ip[0],ip[1])) T=thread (s) t.start () thread_list.append (t) finally:sock.close () for I in Thread_list:i.sock.close () print (' \b\ Blistening exit ')


A lightweight server program, Modbus module is my data related to the logic of processing, commented out.



Python Socket Lightweight Server

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.