我正在开发一个项目,其中带有PiCam的Raspberry Pi 3每10秒拍摄一张照片并通过Python socket
将其发送到远程计算机。我有一个我从this SO question借来的发射器和接收器程序。当我运行代码时,它发送第一个文件没有问题,但是当它尝试发送第二个文件时,我在接收端收到以下错误:
Waiting for a connection.....
Got a connection from ('10.10.10.10', 46490)
File received successfully
Traceback (most recent call last):
File "/home/.../PycharmProjects/PhotoSaver/downloadPhotos.py", line 19, in <module>
size = int(size, 2)
ValueError: invalid literal for int() with base 2: '0\xc3\xa8\x0f \xb0\x19\xc3d\xa3\x00\x00\xf9\x80\xcf9'
这是传输代码:
#!/usr/bin/env python
import threading
class sendPhotos(object):
def __init__(self, host="10.10.10.17"):
self.host = host
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start()
def run(self):
import socket
import os
import thread
from time import sleep, time
from picamera import PiCamera
camera = PiCamera()
camera.resolution = (1024, 768)
camera.start_preview()
#print "Warming up camera"
sleep(2)
#print "Camera started"
s = socket.socket()
host = self.host
#host = socket.gethostname()
port = 9000
s.connect((host, port))
while True:
filename = str(int(time())) + ".jpg"
camera.capture(filename)#Capture image with name as current time
size = len(filename)
size = bin(size)[2:].zfill(16) # encode filename size as 16 bit binary
s.send(size)
s.send(filename)
filename = os.path.join(path,filename)
filesize = os.path.getsize(filename)
filesize = bin(filesize)[2:].zfill(32) # encode filesize as 32 bit binary
s.send(filesize)
file_to_send = open(filename, 'rb')
l = file_to_send.read()
s.sendall(l)
file_to_send.close()
print 'File Sent'
os.system("sudo rm " + filename)
sleep(10)
s.close()
这是接收代码:
import socket import thread import hashlib
serversock = socket.socket() host = "" port = 9000; serversock.bind((host,port)); filename = "" serversock.listen(10); print "Waiting for a connection....."
clientsocket,addr = serversock.accept() print("Got a connection from %s" % str(addr)) while True:
size = clientsocket.recv(16) # Note that you limit your filename length to 255 bytes.
if not size:
break
size = int(size, 2)
filename = clientsocket.recv(size)
filesize = clientsocket.recv(32)
filesize = int(filesize, 2)
file_to_write = open(filename, 'wb')
chunksize = 4096
while filesize > 0:
if filesize < chunksize:
chunksize = filesize
data = clientsocket.recv(chunksize)
file_to_write.write(data)
filesize -= chunksize
file_to_write.close()
print 'File received successfully' serversock.close()
知道导致这种情况的原因是什么? 谢谢,
更新: 在传输代码中,size,int,格式化并发送如下:
size = len(filename)
size = bin(size)[2:].zfill(16) # encode filename size as 16 bit binary
s.send(size)
当使用repr()打印时,它显示为:0\xc3\xa8\x0f \xb0\x19\xc3d\xa3\x00\x00\xf9\x80\xcf9
在我看来,这是套接字和解码格式化的一些问题,有更好的方法吗?