продолжайте получать тайм-аут сеанса, не могу понять почему, сервер должен отобразить сообщение обратно.код отображается внизу, где первый набор кода является клиентом, а второй набор - сервером, первое, что вы увидите, это выходные данные, где показано, что время ожидания сеанса истекло.
Client-Server
All Uppercase
All Lowercase
Initial Caps
Exit
Enter Choice: 1
Enter the sentence: the kid had sicknesss
Session timed out
Это клиент:
import socket
from socket import AF_INET, SOCK_DGRAM
import time
# Address of UDP IP
UDP_IP_ADDRESS = '127.0.0.1' #server set as localhost
# UDP port number
UDP_PORT_NO = 9999
# Display the message
# print('Pinging',UDP_IP_ADDRESS,UDP_PORT_NO)
#create the socket
clientSocket = socket.socket(AF_INET,SOCK_DGRAM)
#sets the timeout at 1 sec
clientSocket.settimeout(1)
choice = 1
try:
print("Client-Server")
# Create a while loop to repeat the process continously
while True:
print()
print("1. All Uppercase")
print("2. All Lowercase")
print("3. Initial Caps")
print("4. Exit")
while(True):
choice=input("Enter Choice: ")
if(choice not in ["1","2","3","4"]):
print("Invalid Input!")
else:
break
if choice is "4":
print( 'Thank you!')
break
# Prompt the user to enter the sentence
sentence=input("Enter the sentence: ")
message=choice+"-"+sentence
# Sending sentence and command to the server.
clientSocket.sendto(message.encode('utf-8'),(UDP_IP_ADDRESS, UDP_PORT_NO))
#"Receiving login request from the server"
#print()
updated_sentence, server = clientSocket.recvfrom(4096)
updated_sentence = str(updated_sentence)
updated_sentence = updated_sentence[2:len(updated_sentence)-1]
print("Updated Sentence from the server: "+updated_sentence)
except socket.timeout:
print( 'Session timed out')
Вот код сервера:
# The following module to generate randomized lost packets
import random
from socket import *
# Create a UDP socket
# Notice the use of SOCK_DGRAM for UDP packets
serverSocket = socket(AF_INET, SOCK_DGRAM)
# Assign IP address and port number to socket
serverSocket.bind(('', 9999))
print('The server is ready to receive on port: 9999')
# Create a 'while-loop' to run the process continoulsy
while True:
# Receive the client packet along with the address it is coming from
message,address = serverSocket.recvfrom(2048)
message = str(message)
message = message[2:len(message)-1]
command = message[0]
sentence = message[2:]
# Create an if-statement to check the command.
if(command == "1"):
sentence=sentence.upper()
elif(command == "2"):
sentence=sentence.lower()
else:
words=sentence.split()
sentence=""
for word in words:
sentence = sentence + word[0].upper()+word[1:]+" "
# Send the modified sentence to the client.
serverSocket.sendto(sentence.encode('utf-8'), address)