我是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
第一个问题:
这是因为您根本没有定义函数
encode/decode_lenght
。第二个问题:
您的函数是:
def _sendFile(self, path): ...
。你知道如何使用
self
?它在课堂上使用。所以不需要self
就定义它,或者使用类:示例:
对
Server
来说也是一样的。在哪里定义这些函数?在暗号里!你的功能应该做什么?
好,举个例子:
关于自我:
只是一点点:
self
重定向到当前对象,例如:someclass.get(c)
如何工作? 在执行someclass.get(c)
时,我们并没有创建someclass
的新实例。 当我们从someclass
实例调用.get()
时,它自动将self
设置到我们的实例对象。所以someclass.get(c)
==c.get()
如果我们试图做someclass.get()
,那么self
没有被定义,因此它将引发一个错误:TypeError: unbound method get() must be called with someclass instance as first argument (got nothing instead)
您可以使用装饰符来调用类的函数(而不是它的实例!)以下内容:
对不起,我的解释不好,我的英语不太好
以下是一些链接:
server.py
client.py
相关问题 更多 >
编程相关推荐