python socket 輕量級服務器

fpcm 10年前發布 | 2K 次閱讀 Python

使用非阻塞加多線程的方式,輕松實現python網絡服務器框架。 工作總結

   由于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模塊是我進行數據的相關處理的邏輯,注釋掉了。

 本文由用戶 fpcm 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!