TCP连接没有第二次给我输出

时间:2018-04-04 16:14:13

标签: python-3.x sockets networking

我已经建立了具有TCP连接的服务器/客户端,它将 bin转换为dec dec转换为bin 并将输出返回给客户端。程序运行正常,只需一次迭代

问题

当我想在不退出程序的情况下再次获得输出(转换)时,我输入一个数字并将该数字发送到服务器,服务器没有响应,光标开始闪烁并且没有输出。我等了5分钟,什么都没发生。

我不明白为什么会发生这种情况

PS:请原谅我的代码,我知道它可以改进。我只想让它一次又一次地显示输出

这是我的代码。 假设导入所有库,并且所有转换函数都正常运行并包含

服务器

print('The server is ready')

message = "yes"
connectionSocket, addr = serverSocket.accept()

while 1:

    while(message == "yes"):

            print(connectionSocket.getpeername())
            sentence = connectionSocket.recv(4096).decode('utf-8')
            number = connectionSocket.recv(4096).decode('utf-8')

            #  binary to decimal conversion
            if(sentence == 'bin_to_dec'):
                    digits = str(binToDec(number))
                    connectionSocket.send(digits.encode('utf-8'))

            # decimal to binary conversion        
            elif(sentence == 'dec_to_bin'):
                    numbers = str(decToBin(number))
                    connectionSocket.send(numbers.encode('utf-8'))

            # If everything fails
            else:
                    print("Wrong input!")
                    connectionSocket.close()

            if(connectionSocket.recv(4096).decode('utf-8') == "no"):
                    break
connectionSocket.close()

客户端

clientSocket.connect((serverName, serverPort))

# flag to check if the user wants to end the input
end_everything = False
again = 'yes'


while(end_everything == False):

# while the user wants to input again
while(again.lower() == "yes"):

    # input
    sentence = str(input('bin_to_dec or dec_to_bin >: '))

    # checking whether the input is correct
    if(sentence.lower() == "bin_to_dec" or sentence.lower() == "dec_to_bin"):

        # inputting the number to convert
        number = str(input("which number or digits you want to convert >: "))

        #encodes the input and sends it to the server
        clientSocket.send(sentence.encode('utf-8'))
        clientSocket.send(number.encode('utf-8'))

        #resonse from the server
        modifiedSentence = clientSocket.recv(4096)

        response = modifiedSentence.decode('utf-8')
        #prints that response
        print('From Server: ', response)

        #prompting user, if they want to input again
        message = input("type 'yes' or 'no' if you want to input again: ")
        if(message.lower() == "yes"):
            #clientSocket.send(message.encode())
            continue

        elif(message.lower() == "no"):
            clientSocket.send(message.encode('utf-8'))
            again = 'no'

        else:
            print("Please enter correct input")
    else:
        print("Not valid input!")
        break


clientSocket.close()

1 个答案:

答案 0 :(得分:1)

首先,是的,你的结束有点粗糙。这实际上有点难以理解,主要是因为我可能不习惯python。 “虽然1”总是疼,但我也是这样。

所以,我的第一个猜测是服务器上的“serverSocket.accept()”调用。看起来您接受连接,接收数据,发送,然后循环并接受新连接。客户方希望一遍又一遍地保留发送消息。

您可能希望serverSocket.accept()在循环时移动到外部,因此它会一直从您的连接中读取,直到它关闭。