我是python套接字编程的新手。我想将5个文件(照片(从mininet中的一个主机传输到另一个主机。这些文件的名称分别编号(我指的是1.jpg、2.jpg和…(。问题是,当我运行这些代码时,第一张照片会正确传输,但其他照片会损坏。问题出在哪里:
sender.py
import socket
import sys
buf = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.0.0.1',12345))
for i in range(1,6):
with open("%d.jpg" % (i),'rb') as f:
data = f.read(buf)
while 1:
if not data:
break
s.sendall(data)
data = f.read(buf)
s.close()
receiver.py:
import socket
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('10.0.0.1', 12345))
buf = 1024
s.listen(1)
conn , addr = s.accept()
for i in range(6,11):
with open("%d.jpg" % (i),'wb') as f:
while 1:
data = conn.recv(buf)
#print(data[:10])
#print "PACKAGE RECEIVED..."
f.write(data)
if not data: break
#conn.close()
#s.close()
问题的简单解决方案是为每个文件创建一个新的连接。下面的代码可以做到这一点。
发件人
from __future__ import print_function
import socket
HOST = 'localhost'
PORT = 12345
BUFSIZE = 4096
def send_file(fname):
with open(fname, 'rb') as f:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((HOST, PORT))
except socket.error as err:
print(err, HOST, PORT)
sock.close()
return
while True:
data = f.read(BUFSIZE)
if not data:
break
while data:
sent = sock.send(data)
data = data[sent:]
sock.close()
fnames = [
'test0.jpg',
'test1.jpg',
'test2.jpg',
'test3.jpg',
]
def main():
for fname in fnames:
send_file(fname)
if __name__ == '__main__':
main()
接收器
from __future__ import print_function
import socket
HOST = 'localhost'
PORT = 12345
BUFSIZE = 4096
def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.bind((HOST, PORT))
except socket.error as err:
print('Bind failed', err)
return
sock.listen(1)
print('Socket now listening at', HOST, PORT)
file_number = 0
try:
while True:
conn, addr = sock.accept()
print('Connected with', *addr)
fname = 'image%d.jpg' % file_number
with open(fname, 'wb') as f:
while True:
data = conn.recv(BUFSIZE)
if not data:
break
f.write(data)
conn.close()
print(fname, 'savedn')
file_number += 1
# Hit Break / Ctrl-C to exit
except KeyboardInterrupt:
print('nClosing')
sock.close()
if __name__ == '__main__':
main()
您需要点击CtrlC或1Break 但在接收器上使用这些数字文件名不是很令人满意,所以我决定让它稍微复杂一点。:(在下面的版本中,我们在文件数据之前发送文件名。这有点棘手,因为接收器需要将文件名与实际文件数据分开。如果每个 为了让接收器知道文件名的结尾,我们首先发送一个对文件名长度进行编码的字节。一个字节可以容纳0到255之间的数字,因此此代码不能处理超过这个数字的文件名。在长度字节之后,我们发送使用UTF-8编码的文件名本身。然后我们发送实际的文件内容。 接收器使用名为receiver的类来处理缓冲。这个类有一个 这段代码有点混乱,因为它被设计为在Python 2和Python 3上以任何组合运行。如果只针对Python3,它会更整洁一些。我硬编码了"localhost"作为主机名,因为我只有一台计算机,所以我无法在网络上测试它,但我相信它在网络上会正确工作。 这是发件人: 这是接收器:socket.recv
调用都对应一个socket.send
调用,这很容易,但不能保证会发生:接收到的字节可能与发送的字节不同。接收器需要缓冲字节,以便能够正确地对它们进行分解。有关详细信息,请参阅套接字编程HOWTO。.get
方法,我们可以使用它来获取指定数量的字节。我们使用该方法来获取文件名长度和文件名。然后我们使用Receiver的.save
方法将接收到的文件内容保存到一个新文件中。from __future__ import print_function
import socket
from struct import pack
HOST = 'localhost'
PORT = 12345
BUFSIZE = 4096
def send(sock, data):
while data:
sent = sock.send(data)
data = data[sent:]
def send_file(fname):
with open(fname, 'rb') as f:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((HOST, PORT))
except socket.error as err:
print(err, HOST, PORT)
sock.close()
return
# Send the file name length & the filename itself in one packet
send(sock, pack('B', len(fname)) + fname.encode())
while True:
data = f.read(BUFSIZE)
if not data:
break
send(sock, data)
sock.close()
fnames = [
'test1.gif',
'test2.jpg',
'test3.png',
'test4.pdf',
]
def main():
for fname in fnames:
send_file(fname)
if __name__ == '__main__':
main()
from __future__ import print_function
import socket
from struct import unpack
HOST = 'localhost'
PORT = 12345
BUFSIZE = 4096
class Receiver:
''' Buffer binary data from socket conn '''
def __init__(self, conn):
self.conn = conn
self.buff = bytearray()
def get(self, size):
''' Get size bytes from the buffer, reading
from conn when necessary
'''
while len(self.buff) < size:
data = self.conn.recv(BUFSIZE)
if not data:
break
self.buff.extend(data)
# Extract the desired bytes
result = self.buff[:size]
# and remove them from the buffer
del self.buff[:size]
return bytes(result)
def save(self, fname):
''' Save the remaining bytes to file fname '''
with open(fname, 'wb') as f:
if self.buff:
f.write(bytes(self.buff))
while True:
data = self.conn.recv(BUFSIZE)
if not data:
break
f.write(data)
def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.bind((HOST, PORT))
except socket.error as err:
print('Bind failed', err)
return
sock.listen(1)
print('Socket now listening at', HOST, PORT)
try:
while True:
conn, addr = sock.accept()
print('Connected with', *addr)
# Create a buffer for this connection
receiver = Receiver(conn)
# Get the length of the file name
name_size = unpack('B', receiver.get(1))[0]
# Get the file name itself
name = receiver.get(name_size).decode()
print('name', name)
# Save the file
receiver.save(name)
conn.close()
print('savedn')
# Hit Break / Ctrl-C to exit
except KeyboardInterrupt:
print('nClosing')
sock.close()
if __name__ == '__main__':
main()
您应该像使用一样使用它
with open("%d.jpg" % (i),'wb') as f:
while 1:
data = conn.recv(buf)
#print(data[:10])
#print "PACKAGE RECEIVED..."
f.write(data)
if not data: break
这样,当您离开with块时,当您退出while时,f会自动关闭。
我想你需要扩展协议,让接收器知道它得到了什么,你可以让它对此采取行动。有点像"转移的开始"。。。发送文件名,发送数据,发送"传输结束",使接收方关闭文件