標籤:
由於Python天生的優點,特別適用於快速實現功能。
#!/usr/bin/python2.7import sysimport timeimport socket#import modbusimport threadingimport selectclass thread(threading.Thread):def __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(1024)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:print(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‘)
一個輕量級伺服器程式,modbus模組是我進行資料的相關處理的邏輯,注釋掉了。
python socket 輕量級伺服器