Python sqlite服务器使用100%的CPU

时间:2017-11-21 09:07:34

标签: python sockets sqlite

我的代码如下。

这是在sqlite3中侦听客户端对数据库的请求的服务器。当我使用系统(debian,rc.local或crontab)运行它时,它使用100%的CPU并且工作非常慢。当我从终端运行它时,非常不舒服,一切正常工作大约一个小时,然后CPU使用率也增长到100%。我猜循环有问题,但我没有看到解决方案。

# -*- coding: utf-8 -*-
#!/usr/bin/python
import select 
import io
import socket 
import sys 
import threading 
import pickle
import struct
import os
import binascii
from os import listdir
from os.path import isfile, join
import sqlite3 
import datetime
import unicodedata
from shutil import copyfile
class Server: 
    def __init__(self): 
        self.host = self.get_ip_address()
        self.port = 50000 
        self.backlog = 5 
        self.size = 1024 
        self.server = None 
        self.threads = [] 

    def get_ip_address(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        return s.getsockname()[0]  
    def open_socket(self): 
        try: 
            self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            self.server.bind((self.host,self.port)) 
            self.server.listen(5) 
        except socket.error, (value,message): 
            if self.server: 
                self.server.close() 
            print "Could not open socket: " + message 
            sys.exit(1) 

    def run(self): 
        self.open_socket() 
        input = [self.server,sys.stdin] 
        running = 1 
        while running: 
            inputready,outputready,exceptready = select.select(input,[],[]) 

            for s in inputready: 

                if s == self.server: 
                    # handle the server socket 
                    c = Client(self.server.accept()) 
                    c.start() 
                    self.threads.append(c) 

                #elif s == sys.stdin: 
                    # handle standard input 
                    #junk = sys.stdin.readline() 
                    #running = 0 

        # close all threads 

        self.server.close() 
        for c in self.threads: 
            c.join() 

class Client(threading.Thread): 
    def __init__(self,(client,address)): 
        threading.Thread.__init__(self) 
        self.client = client 
        self.address = address 
        self.size = 1024 

    def run(self): 
        running = 1 
        while running: 
            sock = self.client
            data = self.recv_msg(sock)
            if data is not None:
                data = pickle.loads(data)
                userid=data[0]
                zap = data[1]
                zap2 = data[2]
                if zap == '1':
                    conn = sqlite3.connect('base.db')
                    zap2 = str(zap2)
                    odp = conn.execute(zap2)
                    data = odp.fetchall()
                    liczba = len(data)
                elif zap == '999':
                    conn = sqlite3.connect('base.db')
                    userid = str(data[0])
                    hour_now = str(datetime.date.today())
                    date_today = str(datetime.datetime.now().time())[:5]
                    conn.execute("update people set hour_end='"+hour_now+"' where userid='"+userid+"' and date='"+date_today+"'")
                    conn.commit()
                data = pickle.dumps(data)
                msg = struct.pack('>I', len(data)) + data
                self.client.sendall(msg)
            else: 
                self.client.close() 
                running = 0 

    def recv_msg(self, sock):
        # Read message length and unpack it into an integer
        raw_msglen = self.recvall(sock, 4)
        if not raw_msglen:
            return None
        msglen = struct.unpack('>I', raw_msglen)[0]
        # Read the message data
        return self.recvall(sock, msglen)

    def recvall(self, sock, n):
        # Helper function to recv n bytes or return None if EOF is hit
        data = ''
        while len(data) < n:
            packet = sock.recv(n - len(data))
            if not packet:
                return None
            data += packet
        return data 

if __name__ == "__main__": 
    s = Server() 
    s.run()

0 个答案:

没有答案