Python Socket 错误:AttributeError: type object 'socket' has no attribute 'socket' 解决方法
出现此错误是因为在您的代码中,您将导入的socket库与socket变量冲突了。为了解决这个问题,请按照以下步骤进行修改:
- 将代码中的所有
socket引用改为其他名称,例如socket_lib。在代码的开头添加以下行:
import socket as socket_lib
- 将所有的
socket替换为socket_lib,包括socket.AF_INET和socket.SOCK_STREAM。例如,将socket.socket(socket.AF_INET, socket.SOCK_STREAM)修改为socket_lib.socket(socket_lib.AF_INET, socket_lib.SOCK_STREAM)。
以下是修改后的代码示例:
import hashlib
import json
import socket as socket_lib
import struct
import os
MAX_PACKET_SIZE = 20480
OP_SAVE, OP_DELETE, OP_GET, OP_UPLOAD, OP_DOWNLOAD, OP_BYE, OP_LOGIN, OP_ERROR = 'SAVE', 'DELETE', 'GET', 'UPLOAD', 'DOWNLOAD', 'BYE', 'LOGIN', 'ERROR'
TYPE_FILE, TYPE_DATA, TYPE_AUTH, DIR_EARTH = 'FILE', 'DATA', 'AUTH', 'EARTH'
FIELD_OPERATION, FIELD_DIRECTION, FIELD_TYPE, FIELD_USERNAME, FIELD_PASSWORD, FIELD_TOKEN = 'operation', 'direction', 'type', 'username', 'password', 'token'
FIELD_KEY, FIELD_SIZE, FIELD_TOTAL_BLOCK, FIELD_MD5, FIELD_BLOCK_SIZE = 'key', 'size', 'total_block', 'md5', 'block_size'
FIELD_STATUS, FIELD_STATUS_MSG, FIELD_BLOCK_INDEX = 'status', 'status_msg', 'block_index'
DIR_REQUEST, DIR_RESPONSE = 'REQUEST', 'RESPONSE'
def _argparse():
parse = argparse.ArgumentParser()
parse.add_argument('--ip', default='', action='store', required=False, dest='ip',
help='The IP address bind to the server. Default bind all IP.')
parse.add_argument('--port', default='1379', action='store', required=False, dest='port',
help='The port that server listen on. Default is 1379.')
parse.add_argument('--f', default='', action='store', required=False, dest='f',
help='The file path. Default is none.')
parse.add_argument('--id', default='2037319', action='store', required=False, dest='id',
help='The id. Default is none.')
return parse.parse_args()
def make_request_packet(operation, data_type, json_data, bin_data=None):
json_data[FIELD_OPERATION] = operation
json_data[FIELD_DIRECTION] = DIR_REQUEST
json_data[FIELD_TYPE] = data_type
return make_packet(json_data, bin_data)
def make_fileRequest_packet(operation, data_type, file_key, file_size, block_index, token, json_data, bin_data):
json_data[FIELD_KEY] = file_key
json_data[FIELD_SIZE] = file_size
json_data[FIELD_TOKEN] = token
json_data[FIELD_OPERATION] = operation
json_data[FIELD_DIRECTION] = DIR_REQUEST
json_data[FIELD_TYPE] = data_type
json_data[FIELD_BLOCK_INDEX] = block_index
return make_packet(json_data, bin_data)
def make_packet(json_data, bin_data=None):
j = json.dumps(dict(json_data), ensure_ascii=False)
j_len = len(j)
if bin_data is None:
return struct.pack('!II', j_len, 0) + j.encode()
else:
return struct.pack('!II', j_len, len(bin_data)) + j.encode() + bin_data
def get_tcp_packet(conn):
bin_data = b''
while len(bin_data) < 8:
data_rec = conn.recv(8)
if data_rec == b'':
time.sleep(0.01)
if data_rec == b'':
return None, None
bin_data += data_rec
data = bin_data[:8]
bin_data = bin_data[8:]
j_len, b_len = struct.unpack('!II', data)
while len(bin_data) < j_len:
data_rec = conn.recv(j_len)
if data_rec == b'':
time.sleep(0.01)
if data_rec == b'':
return None, None
bin_data += data_rec
j_bin = bin_data[:j_len]
try:
json_data = json.loads(j_bin.decode())
except Exception as ex:
return None, None
bin_data = bin_data[j_len:]
while len(bin_data) < b_len:
data_rec = conn.recv(b_len)
if data_rec == b'':
time.sleep(0.01)
if data_rec == b'':
return None, None
bin_data += data_rec
return json_data, bin_data
def login(client_socket, id):
login_data = {
'username': id,
'password': hashlib.md5(id.encode()).hexdigest(),
}
client_socket.send(make_request_packet(OP_LOGIN, TYPE_AUTH, login_data))
json_data, bin_data = get_tcp_packet(client_socket)
return json_data
def get_file_size(file_path):
fsize = os.path.getsize(file_path) # 获取文件大小:以字节为单位
return fsize
def uploadFile(client_socket, fileName, token):
save_data = {}
file_size = get_file_size(fileName)
file_key = str(uuid.uuid4()) + os.path.splitext(fileName)[-1]
client_socket.send(
make_fileRequest_packet(operation=OP_SAVE, data_type=TYPE_FILE, file_key=file_key, file_size=file_size,
block_index=None, token=token, json_data=save_data, bin_data=None))
json_data, bin_data1 = get_tcp_packet(client_socket)
total_block = json_data['total_block']
block_size = MAX_PACKET_SIZE
block_index = 0
while block_index < total_block:
f = open(fileName, 'rb')
f.seek(block_size * block_index)
bin_data = f.read(block_size)
f.close()
client_socket.send(
make_fileRequest_packet(OP_UPLOAD, TYPE_FILE, file_key, file_size, block_index, token, save_data, bin_data))
json_data, bin_data2 = get_tcp_packet(client_socket)
block_index = block_index + 1
print(json_data)
print(type(client_socket))
return file_key
def get_file_md5(filename):
'''
Get MD5 value for big file
:param filename:
:return:
'''
m = hashlib.md5()
with open(filename, 'rb') as fid:
while True:
d = fid.read(2048)
if not d:
break
m.update(d)
return m.hexdigest()
def check_file_state(client_socket, file_key, token):
client_socket.send(
make_fileRequest_packet(operation=OP_GET, data_type=TYPE_FILE, file_key=file_key, file_size=None,
block_index=None, token=token, json_data={}, bin_data=None))
json_data, bin_data = get_tcp_packet(client_socket)
print(json_data)
return json_data['md5']
def main():
parser = _argparse()
server_ip = '10.7.219.224'
server_port = parser.port
file_path = r'C:\Users\DELL\Documents\微信截图_20231007145618.png'
id = parser.id
client_socket = socket_lib.socket(socket_lib.AF_INET, socket_lib.SOCK_STREAM)
client_socket.connect((server_ip, int(server_port)))
json_data = login(client_socket, id)
file_key = uploadFile(client_socket, file_path, json_data['token'])
md5 = check_file_state(client_socket, file_key, json_data['token'])
print(json_data['token'])
print(json_data)
if md5 == get_file_md5(file_path):
print('upload successfully')
client_socket.close()
if __name__ == '__main__':
main()
请确保将server_ip更改为正确的服务器IP地址,并根据您的实际情况设置server_port、file_path和id的值。运行此代码将连接到指定的服务器并执行登录、上传文件和检查文件状态等操作。
原文地址: https://www.cveoy.top/t/topic/kMq 著作权归作者所有。请勿转载和采集!