持续出现会话超时,无法弄清原因,服务器应立即显示该消息

时间:2019-03-22 15:06:16

标签: python networking tcp udp

保持会话超时,无法弄清原因,服务器应立即显示该消息。代码显示在底部,第一组代码是客户端,第二组代码是服务器,您将看到的第一件事是输出,即显示会话超时的位置。

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)

0 个答案:

没有答案