gpt4 book ai didi

python - 客户端通过socket向服务器发送文件

转载 作者:行者123 更新时间:2023-12-01 03:10:40 24 4
gpt4 key购买 nike

我编写了一个客户端和一个服务器程序,其中客户端向服务器发送文件,服务器打印文件的内容。这是代码片段:

Server---------------->serverprog.py

import socket
from threading import *


class Server:
gate = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 0
file = ''

def __init__(self, port):
self.port = port
# self.gate.bind((self.host, self.port))
self.gate.bind(("127.0.0.1", self.port))
self.listen()
def listen(self):
self.gate.listen(10)
while True:
conn,address = self.gate.accept()
self.receiveFilename(conn)
def receiveFileName(self, sock):
buf = sock.recv(1024)
print('First bytes I got: ' + buf)

a = Server(8888)




Client ------------------>clientprog.py

import socket
from threading import *

class Client:
gateway = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#host = socket.gethostname()
host = ''
port = 0
file = ''

def __init__(self, host, port, file):
self.port = port
self.host = host
self.file = file
self.connect()

def connect(self):
self.gateway.connect((self.host, self.port))
self.sendFileName()
self.sendFile()

def sendFileName(self):
self.gateway.send("name:" + self.file)

def sendFile(self):
readByte = open(self.file, "rb")
data = readByte.read()
readByte.close()

self.gateway.send(data)
self.gateway.close()



a = Client('127.0.0.1', 8888, 'datasend.txt')

如果我同时编译客户端和服务器,它会给我服务器程序以下错误:

    Traceback (most recent call last):
File "receivefilepg.py", line 25, in <module>
a = Server(8888)
File "receivefilepg.py", line 15, in __init__
self.listen()
File "receivefilepg.py", line 20, in listen
self.receiveFilename(conn)
AttributeError: Server instance has no attribute 'receiveFilename'

我在这里做错了什么?任何建议都会有帮助!

最佳答案

该错误告诉您所有您需要知道的信息,您在 server.listen 方法中存在拼写错误,而不是调用 self.receiveFileName ,而是调用了 self .receiveFilename.

关于python - 客户端通过socket向服务器发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42915161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com