使用sockets Python发送图像

2024-05-15 21:53:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我对这个代码有一些问题。。。发送的不是整数图像,而是一些字节,有人可以帮助我吗?我想发送我在文件夹中找到的所有图像。谢谢您。

客户

import socket
import sys
import os

s = socket.socket()
s.connect(("localhost",9999))       #IP address, port
sb = 'c:\\python27\\invia'

os.chdir(sb)                        #path

dirs =os.listdir(sb)                #list of file
print dirs

for file in dirs:
   f=open(file, "rb")               #read image
   l = f.read()
   s.send(file)                     #send the name of the file
   st = os.stat(sb+'\\'+file).st_size  
   print str(st)
   s.send(str(st))                  #send the size of the file
   s.send(l)                        #send data of the file
   f.close()
s.close()

服务器

import socket
import sys
import os

s = socket.socket()
s.bind(("localhost",9999))
s.listen(4)                             #number of people than can connect it
sc, address = s.accept()

print address
sb = 'c:\\python27\\ricevi'

os.chdir(sb)
while True:
    fln=sc.recv(5)                      #read the name of the file
    print fln
    f = open(fln,'wb')                  #create the new file
    size = sc.recv(7)                   #receive the size of the file
    #size=size[:7]
    print size
    strng = sc.recv(int(size))          #receive the data of the file 
    #if strng:
    f.write(strng)                      #write the file
    f.close()
sc.close()
s.close()   

Tags: oftheimportsendclosesizeosaddress
2条回答

要在单个套接字上传输一系列文件,您需要某种方式来描述每个文件。实际上,您需要在套接字的顶部运行一个小协议,该协议允许您知道每个文件的元数据,例如其大小和名称,当然还有图像数据。

似乎您正在尝试执行此操作,但是发送方和接收方必须就协议达成一致。

发件人中包含以下内容:

s.send(file)                     #send the name of the file
st = os.stat(sb+'\\'+file).st_size  
s.send(str(st))                  #send the size of the file
s.send(l)

接收者如何知道文件名的长度?或者,接收者如何知道文件名的结尾在哪里,文件的大小从哪里开始?你可以想象接收者得到一个类似foobar.txt8somedata的字符串,并且必须推断文件名是foobar.txt,文件长8字节,包含数据somedata

您需要做的是使用某种delimeter(如\n)来分隔数据,以指示每个元数据的边界。

您可以将包结构设想为<filename>\n<file_size>\n<file_contents>。然后,来自发射机的数据流的示例可能如下所示:

foobar.txt\n8\nsomedata

然后接收器将解码传入流,在输入中查找\n,以确定每个字段的值,例如文件名和大小。

另一种方法是为文件名和大小分配固定长度的字符串,然后是文件的数据。

参数^{}只指定接收数据包的最大缓冲区大小,并不意味着将读取许多字节。

所以如果你写:

strng = sc.recv(int(size))

你不一定会得到所有的内容,特别是当size相当大的时候。

在实际读取size字节之前,您需要在循环中从套接字读取数据,才能使其正常工作。

相关问题 更多 >