使用 Python 通过 TCP 传输文件 [英] Transferring File over TCP using Python
问题描述
我是 python 新手,发现很难理解如何使用带有 tcp 连接的套接字发送文件我在另一个似乎有用的问题中发现了这段代码
I am new to python and finding it really difficult trying to understand how to send files using sockets with a tcp connection i found this code in another question that seems to be useful
客户端
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
现在我对这段代码有两个问题首先
Now i have two problems with this code First
self._con.sendall(encode_length(len(data)))
在这一行中,它给了我一个错误,说 encode_length 未定义
in this line it gives me an error saying encode_length is undefined
其次是发送和接收文件的函数我在哪里打电话给他们我是不是先形成一个 TCP 连接然后调用这些函数以及如何准确调用它们,如果我直接调用它们,它会在客户端给我一个错误,说 _sendFile(self, path) 需要两个参数(因为我不是只传递路径)
Secondly these are functions that send and receive file Where do i call them Do i first form a TCP Connection and then call these functions And how exactly to call them , if i call them directly it gives me an error on client side saying _sendFile(self, path) takes two arguments (since i am not passing self just the path)
第三,我使用 os 库中的函数来获取完整路径,所以我正在调用该函数
Thirdly i am using function from os library to get complete path , So i am calling the function like
_sendFile(os.path.abspath("file_1.txt"))
这是传递参数的正确方法
is this the correct way to pass the argument
对不起,我知道这个问题很基本而且很蹩脚,但在网上我基本上可以得到这个函数,但不知道如何调用它
Sorry i know this question is pretty basic and lame but everywhere online i can basically get the function but not how to call it
现在这就是我调用函数的方式
right now this is how i am calling the function
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"))
这基本上是错误的
我为客户端和服务器使用同一台计算机
I am using the same computer for both Client and Server
使用终端在 Ubuntu 上运行 Python
Running Python on Ubuntu using terminal
推荐答案
第一个问题:
那是因为你还没有定义函数encode/decode_lenght
.
你的函数是:def _sendFile(self, path): ...
.
你知道如何使用self
吗?它在类中使用.所以不用self
来定义它,或者使用类:
Your function is: def _sendFile(self, path): ...
.
Do you know how to use self
? It is used in the classes. So define it without self
, or use classes:
from socket import *
class Client(object):
def __init__(self):
self.clientSocket = socket(AF_INET, SOCK_STREAM)
def connect(self, addr):
self.clientSocket.connect(addr)
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
>>> client = Client()
>>> client.connect(("192.168.0.102", 21000))
>>> client._sendFile(os.path.abspath("file_1.txt")) # If this file is in your current directory, you may just use "file_1.txt"
Server
也一样(几乎).
在哪里定义这些函数?在科西斯的代码中!你的函数应该做什么?
好的,举个例子:
Where to define these functions? In the code ofcorse! What should your functions do?
OK, an example:
def encode_length(l):
#Make it 4 bytes long
l = str(l)
while len(l) < 4:
l = "0"+l
return l
# Example of using
>>> encode_length(4)
'0004'
>>> encode_length(44)
'0044'
>>> encode_length(444)
'0444'
>>> encode_length(4444)
'4444'
<小时>
关于自己:
一点点:
self
重定向到您当前的对象,例如:
self
redirects to your current object, ex:
class someclass:
def __init__(self):
self.var = 10
def get(self):
return self.var
>>> c = someclass()
>>> c.get()
10
>>> c.var = 20
>>> c.get()
20
>>> someclass.get(c)
20
>>>
someclass.get(c)
是如何工作的?在执行someclass.get(c)
时,我们并没有创建someclass
的新实例.当我们从 someclass
实例调用 .get()
时,它自动将 self
设置为我们的实例对象.所以 someclass.get(c)
== c.get()
如果我们尝试执行 someclass.get()
,self
是 not 定义的,所以它会引发错误:TypeError: unbound method get() 必须用某个类实例作为第一个参数调用(什么都没有)
How does someclass.get(c)
work?
While executing someclass.get(c)
, we are not creating an new instance of someclass
.
When we call .get()
from an someclass
instance, it automaticly sets self
to our instance object. So someclass.get(c)
== c.get()
And if we try to do someclass.get()
, self
was not defined, so it will raise an error:
TypeError: unbound method get() must be called with someclass instance as first argument (got nothing instead)
你可以使用 decorator 来调用类的函数(不是它的实例!):
You can use decorator to call functions of a class (not its instance!):
class someclass:
def __init__(self):
self.var = 10
def get(self):
return 10 # Raises an error
@classmethod
def get2(self):
return 10 # Returns 10!
<小时>
对不起,我的解释不好,我的英语不完美
Sorry for my bad explanations, my English is not perfect
这里有一些链接:
这篇关于使用 Python 通过 TCP 传输文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!