我是 python 新手,发现很难理解如何使用带有 tcp 连接的套接字发送文件我在另一个似乎有用的问题中发现了这段代码
客户端
def _sendFile(self, path):
sendfile = open(path, 'rb')
data = sendfile.read()
self._con.sendall(encode_length(len(data))) # Send the length as a fixed size message
self._con.sendall(data)
# Get Acknowledgement
self._con.recv(1) # Just 1 byte
服务器端
def _recieveFile(self, path):
LENGTH_SIZE = 4 # length is a 4 byte int.
# Recieve the file from the client
writefile = open(path, 'wb')
length = decode_length(self.con.read(LENGTH_SIZE) # Read a fixed length integer, 2 or 4 bytes
while (length):
rec = self.con.recv(min(1024, length))
writefile.write(rec)
length -= sizeof(rec)
self.con.send(b'A') # single character A to prevent issues with buffering
现在我对这段代码有两个问题首先
self._con.sendall(encode_length(len(data)))
在这一行中,它给了我一个错误,说 encode_length 是未定义的
其次,这些是发送和接收文件的函数我在哪里调用它们我是否首先形成一个 TCP 连接然后调用这些函数以及如何调用它们,如果我直接调用它们它会给我一个错误在客户端说 _sendFile(self , path) 接受两个参数(因为我没有传递 self 只是路径)
第三,我使用 os 库中的函数来获取完整路径,所以我正在调用函数
_sendFile(os.path.abspath("file_1.txt"))
这是传递论点的正确方法吗
对不起,我知道这个问题非常基础和蹩脚,但在网上任何地方我基本上都可以得到这个功能,但不知道如何调用它
现在这就是我调用函数的方式
serverIP = '192.168.0.102'
serverPort = 21000
clientSocket = socket(AF_INET, SOCK_STREAM)
message = "Want to Backup a Directory"
clientSocket.connect((serverIP, serverPort))
_sendFile(os.path.abspath("file_1.txt"))
这基本上是错误的
我为客户端和服务器使用同一台计算机
使用终端在 Ubuntu 上运行 Python