我正在使用 UDP PYTHON 进行套接字编程,如何保存连接到服务器的客户端,并将该客户端添加到列表中?

I am doing Socket Programming With UDP PYTHON, how can i save client connected to the server, add that client to a list?

我正在使用此代码 服务器:

import socket

ip = "127.0.0.1"
localIP = "127.0.0.1"

localPort = 20001

bufferSize = 1024

msgFromServer = "Hello UDP Client"

bytesToSend = str.encode(msgFromServer)

# Create a datagram socket

UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

# Bind to address and ip

UDPServerSocket.bind((localIP, localPort))

print("UDP server up and listening")

# Listen for incoming datagrams

while (True):
    bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)

    message = bytesAddressPair[0]

    address = bytesAddressPair[1]

    clientMsg = "Message from Client:{}".format(message)
    clientIP = "Client IP Address:{}".format(address)

    client = ip
    if localIP == ip:
        print(clientIP)
        print(clientMsg)
    else:
        print("ip not correct")

    # Sending a reply to client

    UDPServerSocket.sendto(bytesToSend, address)

客户代码:

import socket
import time

count = 0
while count < 5:


    msgFromClient = "Hello"
    bytesToSend = str.encode(msgFromClient)


    serverAddressPort = ("127.0.0.1", 20001)

    bufferSize = 1024

# Create a UDP socket at client side

    UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

# Send to server using created UDP socket

    UDPClientSocket.sendto(bytesToSend, serverAddressPort)

    msgFromServer = UDPClientSocket.recvfrom(bufferSize)

    msg = "Message from Server {}".format(msgFromServer[0])

    print(msg)
    time.sleep(3)

好像客户端的IP被保存到address变量中了。 Python 中的列表语法如下:

listName = ["thing number 1", "thing number 2", 3, "and", 4]

要将条目添加到列表中,您可以使用 .append() 方法

listName.append(address)

祝你好运