- #!/usr/bin/env Python
- # coding=utf-8
- import socket # 导入 socket 模块
- import struct
- from threading import Thread
- import time
- import ast
- import user
- import company
- import crew
- import pymysql
- import equipment
- import overhaul
- import config
- import common
- import os
- import takejudge
- from base import Protocol
- import json
- import metal.standingbook as standingbook
- import metal.MetallicMaterials as metallic
- import metal.MetalPlan as MetalPlan
- import filemanage
- ADDRESS = ('', 7891) # 绑定地址
- FILEADDRESS = ('', 7890) # 绑定服务器接收文件的IP地址
- g_socket_server = None # 负责监听的socket
- file_socket_server = None # 负责监听file的socket
- g_conn_pool = [] # 连接池
- gfile_conn_pool = [] # 连接池
- # BASE_DIR = os.path.dirname(os.path.abspath(__file__))
- BASE_DIR = "/data/"
- ##print('basedir:',BASE_DIR)
- '''
- 接收数据格式:
- 判断方式+
- '''
- def init():
- """
- 初始化服务端
- """
- global g_socket_server,file_socket_server
- g_socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建 socket 对象
- g_socket_server.bind(ADDRESS)
- g_socket_server.listen(128) # 最大等待数(有很多人理解为最大连接数,其实是错误的)
- print("服务端已启动,等待客户端连接...")
- '''接收文件的服务器'''
- file_socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建 socket 对象
- file_socket_server.bind(FILEADDRESS)
- file_socket_server.listen(128) # 最大等待数(有很多人理解为最大连接数,其实是错误的)
- ##print("服务端已启动,等待客户端连接...")
- def accept_client():
- """
- 接收新连接
- """
- while True:
- client, _ = g_socket_server.accept() # 阻塞,等待客户端连接
- ##print(client)
- # 加入连接池
- g_conn_pool.append(client)
- # 给每个客户端创建一个独立的线程进行管理
- thread = Thread(target=message_handle, args=(client,))
- # 设置成守护线程
- thread.setDaemon(True)
- thread.start()
- def accept_file_client():
- """
- 接收新连接
- """
- while True:
- clientfile, _ = file_socket_server.accept() # 阻塞,等待客户端连接
- ##print(client)
- # 加入连接池
- # 给每个客户端创建一个独立的线程进行管理
- thread = Thread(target=file_handle, args=(clientfile,))
- # 设置成守护线程
- thread.setDaemon(True)
- thread.start()
- def pck_handler(client,recvtext):
- """
- 解析数据包
- """
- # 正常数据包定义
- ##print(typesendtext',type(recvtext),recvtext)
- print("第一次",recvtext)
- b2 = recvtext.decode('utf8')
- print(recvtext.decode("utf-8").encode("GBK") )
- ##print("特殊字符转义前:!",b2)
- # body = pymysql.escape_string(b2)
- ##print("特殊字符转义后:!",body)
- user_dict = ast.literal_eval(b2)
- print('user_dist',user_dict)
- '''对内含特殊字符的内容进行批量转义开始'''
- for n in user_dict:
- if type(user_dict[n]) == str:
- ##print(n, pymysql.escape_string(user_dict[n]))
- user_dict[n] = pymysql.escape_string(user_dict[n])
- else:
- pass
- ##print(n, 'is not str')
- '''对内含特殊字符的内容进行批量转义结束'''
- ##print(user_dict['juage'])
- print(user_dict)
- # myddd = str(sendtext, encoding = "utf8")
- ##print(myddd,type(myddd))
- if user_dict['juage'] == 'common':
- ##print(当前在线人数:',len(g_conn_pool))
- if user_dict['name'] == 'getmysqltable':
- #'获得表结构')
- result = common.getmysqltable(user_dict)
- #('result',result)
- elif user_dict['name'] == 'save_tablewidgetdata':
- ##print(获取指定表内的1条数据')
- result = common.save_tablewidgetdata(user_dict)
- ##print(result',result)
- elif user_dict['juage'] == 'user':
- ##print(juage1')
- if user_dict['name'] == 'register':
- ##print(juage2')
- result = user.UserRegister(user_dict)
- ##print(result',result)
- elif user_dict['name'] == 'createsonuser':
- ##print(checklogin')
- result = user.createsonuser(user_dict)
- send_text(client,str(result))
- def send_text(client,senddata):
- ##print('准备发送:',client,"\n",senddata)
- ver = 1
- #
- try:
- body = json.dumps(senddata)#方法1
- except:
- body = str(senddata) # 方法2,强制
- ##print(body,type(body))
- ##print(len(body))
- ##print(body.__len__())
- cmd = 101
- header = [ver, body.__len__(), cmd]
- ##print('header',header)
- headPack = struct.pack("!3I", *header)
- ##print('headPack',headPack)
- sendData1 = headPack + body.encode()
- ##print('sendData1',sendData1)
- client.send(sendData1)
- client.close()
- # # 删除连接
- g_conn_pool.remove(client)
- def dataHandle(client,headPack, bytes):
- # 切割数据包
- while True:
- # 读取包长度
- length_pck = int.from_bytes(bytes[:4], byteorder='little')
- ##print(包长度', length_pck)
- # 截取封包
- pck = bytes[4:4 + length_pck]
- # 删除已经读取的字节
- bytes = bytes[4 + length_pck:]
- ##print(pck, bytes, '把封包交给处理函数')
- # 把封包交给处理函数
- pck_handler(pck, client)
- ##print(2')
- # 如果bytes没数据了,就跳出循环
- if len(bytes) == 0:
- break
- ##print("客户端消息:", bytes.decode(encoding="utf8"))
- def message_handle(client):#用于接收服务器发过来的分包数据
- """
- 消息处理
- """
- # FIFO消息队列
- ##print("FIFO消息队列")
- dataBuffer = bytes()
- ##print("databuffer:",type(dataBuffer))
- # 自定义消息头的长度
- headerSize = 12
- # 定义数据包的个数
- sn = 0
- # client.sendall("lianjiechenggong!".encode(encoding='utf-8'))
- while True:
- try:
- data = client.recv(1024)
- len(data)
- if data:
- # 把数据存入缓冲区,类似于push数据
- dataBuffer += data
- while True:
- if len(dataBuffer) < headerSize:
- ##print("数据包(%s Byte)小于消息头部长度,跳出小循环" % len(dataBuffer))
- break
- # 读取包头
- # struct中:!代表Network order,3I代表3个unsigned int数据
- headPack = struct.unpack('!3I', dataBuffer[:headerSize])
- bodySize = headPack[1]
- # 分包情况处理,跳出函数继续接收数据
- if len(dataBuffer) < headerSize + bodySize:
- ##print("数据包(%s Byte)不完整(总共%s Byte),跳出小循环" % (len(dataBuffer), headerSize + bodySize))
- break
- # 读取消息正文的内容
- body = dataBuffer[headerSize:headerSize + bodySize]
- # 数据处理
- ##print("接收到的完整信息:!",body)
- ##print("接收到的完整type:!",type(body))
- # body = pymysql.escape_string(body)
- ##print("特殊字符转义后:!",body)
- pck_handler(client,body)
- # 数据出列
- dataBuffer = dataBuffer[headerSize + bodySize:] # 获取下一个数据包,类似于把数据pop出
- except Exception as e: # 意外掉线
- ##print("---------------------------")
- ##print("客户端断开了。" )
- # client.close()
- # 删除连接
- # g_conn_pool.remove(client)
- break
- def file_handle(fileclient):#用于接收服务器发过来的文件分包数据
- """
- 上传文件处理
- """
- while True:
- data = ''
- data = fileclient.recv(1024) #开始接收
- ##print(data)
- ##print(str(data,'utf8'))
- file_size,savepath,newname = str(data,'utf8').split('|')
- # path = os.path.join(BASE_DIR,'yuan',filename)
- # 判断文件夹是否存在,不存在,就创建
- path = os.path.join(BASE_DIR,savepath)
- if os.path.exists(path) == False: #
- os.makedirs(path)
- path = os.path.join(BASE_DIR, savepath, newname)
- ##print(path)
- file_size = int(file_size)
- ##print(file_size,savepath,newname)
- f = open(path,'ab')
- has_receive = 0
- while has_receive != file_size:
- data = fileclient.recv(1024)
- f.write(data)
- has_receive += len(data)
- ##print('接收数据',has_receive,file_size)
- ##print('接收数据完成', has_receive, file_size)
- f.close()
- break
- ##print('关闭当前连接')
- fileclient.close()
- if __name__ == '__main__':
- init()
- # 新开一个线程,用于接收新连接
- thread = Thread(target=accept_client)
- thread.setDaemon(True)
- thread.start()
- threadfile = Thread(target=accept_file_client)
- threadfile.setDaemon(True)
- threadfile.start()
- config.mysql
- while True:
-
- if len(g_conn_pool)==0:
- time.sleep(5)
-
- for i in g_conn_pool:
- ##print(i)
- time.sleep(5)
复制代码
求助:python在宝塔管理项目运行时CPU占用严重。
以前在windows系统下运行挺好,现在将python程序通过centos的宝塔面板python管理项目运行,CPU占用严重。python版本:3.7.8
框架:python
启动方式:python
|
|