由于Python天生的优点,特别适用于快速实现功能。
#!/usr/bin/python2.7 import sys import time import socket #import modbus import threading import select class thread(threading.Thread): def __init__(self,sock): threading.Thread.__init__(self) #self.commond=modbus.modbus() self.sock=sock def run(self): time1=time.time()-10 time2=time.time() try: while True: cr,cw,ce=select.select([self.sock],[],[self.sock],1) time2=time.time() if cr:#//can read stream=self.sock.recv(1024) if not stream: break #self.commond.parse(stream) if ce: break if 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模块是我进行数据的相关处理的逻辑,注释掉了。
时间: 2024-10-09 13:56:49