У меня есть один сервер и два клиента или, возможно, в будущем. У меня нет проблем с получением изображений от одного клиента, но когда несколько клиентов пытались отправить свои изображения, он прекращает получать и отправлять с обеих сторон. Я использовал блокировку и поток, чтобы позволить каждому клиенту использовать dataTransfer (). В чем здесь проблема? Мой собственный гость - сокет не может определить конец потока.
Server.py
import socket
import sys
import threading
from threading import Thread
from time import time
from time import sleep
host = "192.168.200.1"
port = 5560
t = 0
def setupServer():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
print("Socket created.")
try:
s.bind((host, port))
except socket.error as msg:
print(msg)
print("Socket bind comlete.")
return s
def setupConnection():
s.listen(0) # Allows one connection at a time.
conn, address = s.accept()
print("Connected to: " + address[0] + ":" + str(address[1]))
return conn
def storeFile(fn):
global t
print(fn)
picFile = open("C:\\Users\\Win7\\Desktop\\Image\\" + fn, 'wb')
print("Ready to save file.")
try:
pic = conn.recv(1024*1024)
t = time()
while pic:
#print("Receiving picture still.")
picFile.write(pic)
pic = conn.recv(1024*1024)
print("Finish Writing File")
picFile.close()
print("Time Taken : " + str(time() - t) + "s")
except:
print("Trying to Receieve")
def dataTransfer(conn, addr):
while True:
print("Thread started numer: " + str(threading.active_count()))
print("Acquiring Lock - " + addr)
if not lock.acquire(False):
print("Failed to Acquire Lock... Sleeping for 0.5 seconds.")
sleep(0.5)
else:
print("Acquired Lock - " + addr)
try:
# A big loop that sends/receives data until told not to.
# Receive the data
data = conn.recv(1024) # receive the data
data = data.decode('utf-8')
conn.send(str.encode("GO"))
storeFile(data)
print("Connection Leaving.")
conn.close()
print("Socket Closed.")
finally:
lock.release()
print("Released Lock - " + addr)
break
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
lock = threading.Lock()
s.listen(5) # Allows one connection at a time.
while True:
try:
conn, address = s.accept()
t = Thread(target=dataTransfer, args=(conn, str(address)))
t.start()
except:
print("Unexpected error:", sys.exc_info()[0])
break
Client.py
import socket
from time import sleep
from time import time
host = '192.168.200.1'
port = 5560
def setupSocket():
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
return s
def sendPic(s,filePath,filename):
print(filePath)
print(filename)
pic = open(filePath,'rb')
chunk = pic.read(1024*1024)
s.send(str.encode(filename))
t = time()
check = s.recv(1024)
check = check.decode('utf-8')
while chunk and check:
print("Sending")
s.send(chunk)
chunk = pic.read(1024*1024)
if not chunk:
break
pic.close()
print("Done Sending")
print("Elapsed time = " + str(time() -t) + 's')
s.close()
return "Done Sending"
def transfer(filePath,filename):
print("called")
s = setupSocket()
response = sendPic(s,filePath,filename)
return response
Результат сервера
Thread started numer: 2
Acquiring Lock - ('192.168.200.2', 59536)
Acquired Lock - ('192.168.200.2', 59536)
2018-10-29_225335-0_5741.JPG
Ready to save file.
Thread started numer: 3
Acquiring Lock - ('192.168.200.3', 35514)
Failed to Acquire Lock... Sleeping for 0.5 seconds.
Thread started numer: 3
Acquiring Lock - ('192.168.200.3', 35514)
Failed to Acquire Lock... Sleeping for 0.5 seconds.
Результат клиента
Failed to create the new directory.
Renamed the JPG
Sending
Sending