TCP 服务器 - 客户端 - 第一次连接后通信结束

问题描述 投票:0回答:0

我是 Python 的新手(仅 3 天),我有一个任务需要创建一个 TCP 客户端,它可以要求用户输入数字,验证它,将它与前 n 个自然数相加,然后将它发送到收到总和数的 TCP 服务器生成另一个总和数并发回结果。 我能够创建两者并让它工作到服务器收到总数的地步。

我在这之后写的任何其他东西,根本不起作用,就像它根本不存在一样。

请帮忙

**TCP 服务器代码**

import random
import socket
HOST = '127.0.0.1'
PORT = 7070

#Create Server Socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#Associate the Server socket with the Server port number.
server.bind((HOST, PORT))
# wait for clients to start communications with maximum 5 queued connections.
server.listen(100)
# Displaying the Server name.
print ("The server is ready to receive.")


while True:
    #Create Connection Socket
    communication_socket, address = server.accept()
    print(f"Connected to {address}")

    #Recieve the message from client.
    message = communication_socket.recv(2048).decode('utf-8')
    print(f"Message from Client is: {message}")



    # Generate a random number.
    ServerNumber = random.randint(1, 51)
    print(f"The random number in the range of 1-50 is: {ServerNumber}")

    message = communication_socket.recv(2048).decode('utf-8')

    # Send the message
    communication_socket.send(f"From the Server: {ServerNumber}".encode('utf-8'))

    communication_socket.send(ServerNumber.encode('utf-8'))



    # Close communication with client
    communication_socket.close()

TCP 客户端代码

import socket

# Create Server
HOST = '127.0.0.1'
PORT = 7070

# Create client socket (IPv4, TCP socket)
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Ask for connection to server
socket.connect((HOST, PORT))
# Announce the Client Name
print("This is the client.")


number = int(input("Enter a number in the range of 1-20: "))

while not int(number) in range(1, 21):
        number = input("Invalid Integer! The number must be in range of 1-20: ")
        print("The number is: " + number)

# Calculate the sum of the first n natural number
n = int(number)
sum = 0
# loop from 1 to n
for num in range(1, n + 1, 1):
    sum = sum + num



# Start communication with the server.
while 1:
    # Send message with the sum number
    socket.send(str(sum).encode("utf8"))

**
# THIS IS where anything I write Afterwords doesn't show up**

    # Receive from server
    print(socket.recv(2048).decode('utf-8'))


    # Send the modified message
    communication_socket.send(bytes(own_message, "utf-8"))
    communication_socket.send(bytes(ServerNumber, "utf-8"))
    communication_socket.send(bytes(add_number, "utf-8"))

    # Close connection
    socket.close()
python sockets tcpclient sendmessage tcpserver
© www.soinside.com 2019 - 2024. All rights reserved.