简体   繁体   English

在Python 3中通过套接字发送图像

[英]Sending images over socket in Python 3

I am trying to send an image (screenshot) over socket from the client to the server. 我正在尝试通过套接字从客户端向服务器发送图像(屏幕快照)。 In Python 2 I was able to use the read() and write() function in order to read and write binary data as well as StringIO . 在Python 2中,我能够使用read()write()函数来读取和写入二进制数据以及StringIO But all of them disappeared in Python 3. I was playing around with PIL , but I can't get the test program running. 但是所有这些都在Python 3中消失了。我在玩PIL ,但是我无法运行测试程序。

CLIENT 客户

image = ImageGrab.grab()
s.send(image.tobytes())

I create a screenshot using GrabImage and save it as image . 我使用GrabImage创建屏幕截图并将其另存为image After that I send the image as binary over the socket to the server. 之后,我将图像作为二进制文件通过套接字发送到服务器。

SERVER 服务器

data = conn.recv(4194304)
img = Image.frombytes('RGB', (1366, 768), data)
img.save('screenshot.jpg')

However, If I run the script I get an error message: 但是,如果我运行脚本,则会收到错误消息:
ValueError: not enough image data

I think I'm missing something decisive, but I can't figure it out. 我想我缺少决定性的东西,但我无法弄清楚。
Thank you, chrizator. 谢谢你,主持人。

It's likely that the call to .recv() is returning before all the data is retrieved; 在检索所有数据之前,很可能返回对.recv()的调用。 the parameter is a maximum size, not an exact size. 该参数是最大大小,而不是确切大小。 You'll need to call .recv() in a loop and append the data until the entire image is received. 您需要循环调用.recv()并追加数据,直到接收到整个图像为止。 This implies that you'll need some way to know WHEN the entire data is received - common strategies for this are: 这意味着您需要某种方式来知道何时接收到全部数据-常见的策略是:

  • Keep reading until you see some particular terminating character or character sequence. 继续阅读,直到看到某些特定的终止字符或字符序列。 Not directly applicable in this case, since the raw image data could accidentally contain any particular sequence of bytes whatsoever. 在这种情况下不直接适用,因为原始图像数据可能会意外地包含任何特定的字节序列。
  • Send the length (perhaps as a decimal number with a terminator, or a fixed-size binary value) ahead of the data; 在数据之前发送长度(可能是带终止符的十进制数字,或固定大小的二进制值); keep reading until you've received that many bytes. 继续阅读,直到收到那么多字节。
  • Close the socket after sending the data; 发送数据后关闭套接字; keep reading until you get a zero-byte result. 继续阅读,直到得到零字节的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM