【问题标题】:Pygame not working with socketsPygame 不能使用套接字
【发布时间】:2011-10-03 00:16:18
【问题描述】:

我用 pygame、imageGrab 和套接字创建了一个程序,但它不起作用。它应该使用 ImageGrab 获取服务器的打印屏幕,将其转换为字符串,然后将其发送到客户端。但是,客户端在收到信息并将其转换为图像时会引发错误:

image = pygame.image.frombuffer(img, (800,600), "RGB")
ValueError: Buffer length does not equal format and resolution size 

代码服务器

import sys, os, socket, pygame
from PIL import ImageGrab
from pygame.locals import *
print "streaming sever 0.1"
try:
    socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

except socket.error:
    print "Error creating socket"
    sys.exit(1)

host = "127.0.0.1"
port = raw_input("Port:")

socket.bind((host, int(port)))
socket.listen(2)

socket2,client = socket.accept()
print "Client conectado: " + str(client[0]) + "\nPorta usada: " + str(client[1])


#Capture and send

while True:
    img=ImageGrab.grab().resize((800,600))
    img.tostring()
    socket2.sendall(img)

socket2.close()

代码客户端

import sys, os, socket, pygame
from PIL import ImageGrab
from pygame.locals import *
print "streaming client 0.1"

pygame.init()

try:
  s_client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  print "streaming protocol started"
except socket.error:
  print "Error creating socket"
  sys.exit(1) 

host = "127.0.0.1"
porta = raw_input("Port:")
q_bytes = raw_input("Enter the number of MBs to transfer: ")

t_bytes = 1024*1024*int(q_bytes)

try:
  s_client.connect((host,int(porta)))
except socket.error:
  print "Error connecting to: " + host
  sys.exit(1)
print "Conectado!"



size = width, height = 800, 600
screen = pygame.display.set_mode(size)

num = 0

while True:
  img = s_client.recv(t_bytes)
  image = pygame.image.frombuffer(img, (800,600), "RGB")
  screen.blit(image,(0,0))
  pygame.display.flip()
  for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            os._exit(1)
#recebimento

s_client.close()

【问题讨论】:

  • 致寻找 ImageGrab 的其他人;显然它只是 Windows。
  • docs.python.org/howto/sockets.html#using-a-socket 显然曾经有葡萄牙语翻译,但现在链接已断开。
  • thomas 我修改了代码以接收小图像,并在硬件问题上给出了相同的错误,您可以更好地解释可能发生的事情,就像两个的力量一样,您可以向我解释我做什么这个错误核心?谢谢,布鲁诺·特里波洛尼

标签: python sockets pygame


【解决方案1】:

与套接字的处理是,如果您打算继续使用相同的套接字连接,您必须确切地知道您收到的消息多长时间。您的q_bytes = raw_input("Enter the number of MBs to transfer: ") 似乎对此有所了解,但我们需要准确地了解,而不是最接近的 MB。有时这个信息是在数据的最前面发送的,所以我们可以先读取它,然后知道什么时候停止读取。

如果我们不再需要连接,则例外;我们只想要这张照片。在这种情况下,我们可以请求尽可能多的数据,最后我们会得到一个空字符串。

至于 recv 的 max_bytes 参数,这只是一个最大值 - 还有另一个取决于硬件的最大值强加给我们,在我的测试中它是 1MB。

下面的代码只是不断地请求数据,当它收到一个空字符串时停止,因为没有更多的数据,然后将所有这些收集的数据组合成完整的字符串。

可以(并且应该)构建许多抽象级别以使我们远离这些复杂性,但下面的代码只是您的,正在工作,删除了一些不相关的部分。

客户端.py

import sys, os, socket, pygame
from pygame.locals import *

pygame.init()

s_client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

host = "127.0.0.1"
porta = 12350
t_bytes = 1024*1024*1

s_client.connect((host,int(porta)))
print "Conectado!"

size = width, height = 300, 500
screen = pygame.display.set_mode(size)

message = []
while True:
    s = s_client.recv(t_bytes)
    if not s:
        break
    else:
        message.append(s)
full_s = "".join(message)
print 'string received size', len(full_s)
image = pygame.image.frombuffer(full_s, size, "RGB")
#image = pygame.image.fromstring(s, size, "RGB")
screen.blit(image,(0,0))
pygame.display.flip()
for event in pygame.event.get():
    if event.type == QUIT:
        pygame.quit()
        os._exit(1)
    raw_input()

s_client.close()

服务器.py

import sys, os, socket, pygame
from pygame.locals import *

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 12350
socket.bind((host, int(port)))
socket.listen(2)
socket2,client = socket.accept()
print "Client conectado: " + str(client[0]) + "\nPorta usada: " + str(client

img = Image.open('tiny.jpg').resize((300, 500))
s = img.tostring()
print 'size of string', len(s)
socket2.sendall(s)

socket2.close()

edit:根据 Mark 的更正,len() 调用以前是 __sizeof__() 方法调用。 __sizeof__ 以字节为单位返回 python 对象的大小,而不是字符串中的字节/字符数。

【讨论】:

  • 小改进:len(s) 而不是s.__sizeof__()
猜你喜欢
  • 2021-11-16
  • 2017-09-14
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
  • 2011-06-13
  • 2021-12-18
  • 1970-01-01
  • 2021-06-24
相关资源
最近更新 更多