我正在处理客户机/服务器tcp项目,我想知道哪种“检查”服务器/客户机已准备好要发送数据的好方法。 这是因为我的客户有一个GUI,并且我希望服务器随时准备好进行任何输入,因此应确保服务器在发送数据时不尝试发送数据
这是我的尝试
客户:
import socket
# Methods of a class
def receiveData(self, FROM=""):
if self.SENT_LAST:
print("DATA WAS LAST SENT BY CLIENT, NO CHECK REQUIRED")
else:
print("DATA LAST SENT BY CLIENT, CHECK REQUIRED")
self.sendPickledData("dataReady")
print("In receive data")
if FROM:
print("From:", FROM)
data = s.recv(4096)
try:
data = pickle.loads(data)
except pickle.UnpicklingError as err:
errorReport(err)
time.sleep(0.2)
self.SENT_LAST = False
if data != noData:
print("data :",data)
return data
else:
print("No data found")
return False
def sendPickledData(self, data, FROM=""):
if self.SENT_LAST:
print("DATA WAS LAST SENT BY CLIENT, CHECK REQUIRED")
checkData = self.receiveData("sendpickled")
print("CheckData :", checkData)
if checkData != "dataReady":
raise ValueError
else:
print("DATA LAST SENT BY CLIENT, NO CHECK REQUIRED")
print("In sendPickle, data :", data)
if FROM:
print("From:", FROM)
data = pickle.dumps(data)
s.sendall(data)
time.sleep(0.5)
self.SENT_LAST = True
print("Data sent")
服务器:
import socket
def receiveData_v2(FROM, FUNC=[]):
global SENT_LAST, receive_count
receive_count += 1
print("Receive :",receive_count)
print("Receiving")
if SENT_LAST:
print("DATA WAS LAST SENT BY SERVER, NO CHECK REQUIRED")
if not SENT_LAST:
print("DATA LAST SENT BY SERVER, CHECK REQUIRED")
sendPickledData("dataReady")
SENT_LAST = False
print("In receive data")
if FROM:
print("From:", FROM)
data = conn.recv(4096)
try:
data = pickle.loads(data)
except pickle.UnpicklingError as err:
print("Pickling error:")
print(err)
if data == PROG_QUIT:
return data
elif data == noData:
return False
else:
if FUNC:
funcData = FUNC(data)
return funcData
else:
return data
def sendPickledData(data):
global SENT_LAST, send_count
send_count += 1
print("Send :",send_count)
print("sending")
if SENT_LAST:
print("DATA WAS LAST SENT BY SERVER, CHECK REQUIRED")
print("sent last")
checkData = receiveData_v2("sendpickled")
print("CheckData :", checkData)
if checkData != "dataReady":
raise ValueError
else:
print("DATA LAST SENT BY SERVER, NO CHECK REQUIRED")
print("In sendPickled,\nSending:", data)
data = pickle.dumps(data)
conn.sendall(data)
SENT_LAST = True
conn.sendall(data)
每当我尝试通过这种方法发送数据时,都会以某种方式最终导致不同步,并且它们最终都将试图同时监听数据。否则receiveData(客户端)将仅收到“ dataReady”