我正在尝试将文件从客户端(raspberry pi)发送到服务器。但是由于某种原因,我的代码一直在中断。从错误中我得到的问题是,客户端正在读取刚发送给服务器的文件数据。不确定如何解决。
这是我的代码:
# Server
import socket
import sys
import threading
TCP_PORT = 9999
# TCP_IP = "localhost"
TCP_IP = "192.168.0.100"
# all slaves are on the same subnet (192.168.1.1/24)
class send(object):
def take_picture_request(self, TCP_IP, TCP_PORT):
s = socket.socket()
s.connect((TCP_IP, TCP_PORT))
s.send("1".encode('utf-8'))
print("Request Sent to: ", str(TCP_IP))
def recieving_file(self):
s = socket.socket()
s.bind(("0.0.0.0", TCP_PORT))
# s.bind(("192.168.0.109",9999))
s.listen(100) # Accepting 100 connections
print("listening on port: 9999")
i = 1
while True:
print("Accepting Connections")
sc, address = s.accept()
# print(address)
sc.recv(1024)
print (address)
f = open('file_'+ str(i)+".jpeg",'wb') #open in binary
i=i+1
print("Reciving file data")
while (True):
# reciving and writing the file
l = sc.recv(1024)
f.write(l)
if not l:
break
f.close()
sc.close()
print('copied the file.')
def menu():
print("MENU")
print("1 - Take Picture")
print("2 - Exit")
ui = input(": ")
if ui == "1":
# for i in range(24):# number of ip that you want to send the request to
# TCP_IP = "192.168.0.10" + str(i)
# creates the number of threads needed to send requests to
# thread = threading.Thread(target=send().take_picture_request(TCP_IP, TCP_PORT), args=(TCP_IP, TCP_PORT,))
# thread.start()
send().take_picture_request(TCP_IP, TCP_PORT)
send().recieving_file()
# _thread.start_new_thread(send().take_picture_request(TCP_IP, TCP_PORT), ())
elif ui == "2":
sys.exit(0)
else:
print("Invalid input")
menu()
menu()
这是客户端的代码 #客户 进口插座 导入时间 从picamera导入PiCamera
# take a picture using the webcam
def take_picture():
print("Taking Picture")
with PiCamera() as camera:
camera.resolution = (1280, 720)
fname = "/home/pi/" + str(time.time()) + ".jpg"
print("Saving picture: " + fname)
camera.capture(fname)
return fname
# send the picture to the server
def send_file_to_server(fname, TCP_IP, TCP_PORT):
s = socket.socket()
s.connect((TCP_IP, TCP_PORT))
print("Client: Connection Established")
print("Client: Opening file " + fname + ".jpg")
f = open(fname, "rb")
l = f.read(1024)
while (l):
print("Client: Sending file to server")
s.send(l)
l = f.read(1024)
s.close()
print("Client: File " + fname + " sent")
# listens for instructions from the server
def start_listening():
TCP_PORT = 9999
# TCP_IP = "localhost"
TCP_IP = "0.0.0.0"
s = socket.socket()
print("Binding to IP and PORT")
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
print("Started Listening")
while True:
conn, address = s.accept()
connection = conn.recv(1024)
print("Checking for valid response")
# print(connection)
if connection.decode('utf-8') == "1":
print("Response is valid")
fname = take_picture()
send_file_to_server(fname, TCP_IP, TCP_PORT)
print("Picture Taken and Sent to Server")
def main():
print("Calling the start_listening function")
# start_listen for instructions
start_listening()
main()
提前感谢所有帮助