Я пытаюсь научиться делать стандартные вещи клиент / сервер в Python, и я пытаюсь создать метод, который в основном говорит мне, отправляет ли мой клиент данные на мой сервер (localhost). Я хочу, чтобы он использовалsocket.timeout, если я ничего не отправлял в течение 3 секунд.
Я пытался создать метод "heartbeat", но я не могу понять, как дать ему правильный ввод в его параметрах,Вероятно, было бы также более оптимальным использовать мой sock.sendto для отправки данных.
import socket
import re
import time
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
clientAddress = ('localhost', 10000)
clientData = b'com-0'
toleranceMessageServer = b'con-res0xFF'
heartbeatMessage = b'con-h 0x00'
clientOn = True
serverData = ""
def options():
with open("optConf.txt", "r") as f:
file = f.read()
# print(file)
split = re.split(" : | \s", file)
# print(split)
if split[1] == "True":
sock.sendto(heartbeatMessage, clientAddress)
elif split[1] == "False":
print("Heartbeat is:", split)
sock.close()
def heartbeat(seconds):
start = time.time()
elapsed = 1
while elapsed < seconds:
elapsed = time.time() - start
# print("loop cycle time: %02d" % elapsed)
time.sleep(1)
if elapsed >= 3:
# THIS IS WHEERE I WANT TO TIMEOUT
if elapsed < 3:
elapsed = 0
try:
while clientOn:
try:
if clientData == b'com-0':
# printing and sending first message to server
print('C: {} {}'.format(clientData.decode('utf-8'), clientAddress[1]))
sock.sendto(clientData, clientAddress)
heartbeat(3)
time.sleep(1)
# Receive from server
serverData, serverAddress = sock.recvfrom(5000)
# Receive data from server, decodes and split
dataDecoded = serverData.decode('utf-8')
# print("S:", dataDecoded)
splitData = re.split(r"-|\s|=", dataDecoded)
# print(splitData)
# Receive accept and sends msg-0=hello, i am new user
if splitData[0] == "com" and splitData[1] == "0" and splitData[2] == "accept":
print("S:", dataDecoded, serverAddress[0])
time.sleep(1)
print("C: com-0 accept")
time.sleep(1)
clientData = b"msg-0=hello, i am new user"
print("C:", clientData.decode("utf-8"))
time.sleep(1)
sock.sendto(clientData, clientAddress)
heartbeat(3)
# Receive res-1=i am server and sends msg-2=OK, good to know
if splitData[0] == "res" and splitData[1] == "1":
print("S:", dataDecoded)
time.sleep(1)
clientData = b'msg-2=OK, good to know'
print("C:", clientData.decode("utf-8"))
time.sleep(1)
sock.sendto(clientData, clientAddress)
heartbeat(3)
# Data input from client to server
if splitData[0] == "res" and splitData[1] == "3":
print("S:", dataDecoded[6:])
time.sleep(1)
print("[CLIENT] YOU CAN NOW SEND DATA TO SERVER")
clientData = input()
messageList = ["[CLIENT]", clientData]
messageListToString = ' '.join(messageList)
messageListToBytes = bytes(messageListToString, 'utf-8')
sock.sendto(messageListToBytes, clientAddress)
heartbeat(3)
# breaks while loop
if clientData == "quit":
clientOn = False
# test for timeout
if clientData == "wait":
print("waiting 5 seconds")
time.sleep(5)
# statement for handling tolerance and package size
if splitData[0] == "con" and splitData[1] == "res0xFE" or dataDecoded == "THE PACKAGE IS TOO BIG":
clientData = b'com-0'
if dataDecoded == "THE PACKAGE IS TOO BIG":
print(dataDecoded)
else:
print("[CLIENT] SENDING:", toleranceMessageServer)
sock.sendto(toleranceMessageServer, clientAddress)
heartbeat(3)
# if server is not responding
except (socket.timeout, ConnectionResetError) as e:
err = e.args[0]
# print(err)
if err == 10054:
print("[CLIENT] NO SERVER CONNECTION")
time.sleep(2)
continue
if err == 'timed out':
try:
clientData = b'com-0'
print("[CLIENT] SENT HEARTBEAT TO SERVER")
options()
except TypeError:
print("[CLIENT] NO SERVER CONNECTION")
time.sleep(1)
continue
finally:
sock.close()