我正在尝试从服务器向客户端发送屏幕截图(使用PIL)。
截图部分工作正常,但是当我尝试发送图像时它不起作用。当我尝试创建图像时,不会创建该文件。我认为问题在于我发送数据的方式。
我读到我必须在传输文件之前将文件大小发送给客户端,但我不明白该怎么做。
服务器:
import socket
from random import randint
from PIL import ImageGrab
SIZE = 1024
def main():
while True:
try:
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8820))
server_socket.listen(1)
(client_socket, client_address) = server_socket.accept()
data = client_socket.recv(1024)
if data == "SCREEN":
image = ImageGrab.grab()
image.save(r'C:\Users\Dennis\Desktop\Python\ScreenShots\screen.jpg')
file = open('C:\Users\Dennis\Desktop\Python\ScreenShots\screen.jpg', 'rb')
content = file.read()
while content:
current = content[:SIZE]
content = content[SIZE:]
client_socket.send(current)
file.close()
if data == "EXIT":
client_socket.send("Disconnected")
break
else:
print "error"
# in case client disconnected
except socket.error:
print "Connection was lost."
client_socket.close()
server_socket.close()
if __name__ == '__main__':
main()
客户端:
import socket
def main():
while True:
my_socket = socket.socket()
my_socket.connect(('127.0.0.1', 8820))
my_socket.send(raw_input())
content = ''
while True:
data = my_socket.recv(1024)
if not data:
break
content += data
with open ('C:\Users\screennew.jpg', 'wb') as f:
f.write(content)
if data == "Disconnected":
break
my_socket.close()
if __name__ == '__main__':
main()
非常感谢,我将不胜感激。