如何在Python的其余线程中唯一地标识每个客户机线程

2024-04-23 06:49:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我找不到唯一的方法来标识服务器上创建和保留的每个线程。每个客户机线程都必须存储自己的信息,这些信息用于将信息中继回其各自的客户机。省略了创建服务器的明显细节:

import sys
from threading import Thread
import socket
import traceback


def client_thread(conn, ip, port, MAX_BUFFER_SIZE = 4096):
    while 1:
    # the input is in bytes, so decode it
        input_from_client_bytes = conn.recv(MAX_BUFFER_SIZE)
            if not input_from_client_bytes:
                break

        # decode input and strip the end of line
        input_from_client = input_from_client_bytes.decode("utf8").rstrip()
        aString = ''
        if (input_from_client.startswith('LOAD BOARD')):
            array = input_from_client.split('~')
            aString = array[1]
        vysl = aString.encode("utf8")  # encode the result string
        conn.sendall(vysl)  # send it to client
    conn.close()  # close connection
    print('Connection ' + ip + ':' + port + " ended")

    while True:
        conn, addr = soc.accept()
        ip, port = str(addr[0]), str(addr[1])
        print('Accepting connection from ' + ip + ':' + port)

        try:
            Thread(target=client_thread, args=(conn, ip, port)).start()
        except:
            traceback.print_exc()
    soc.close()

start_server() 

我读到的一个建议是创建一个python文件,并在其中添加所有变量,然后将其导入服务器,但是如果所有其他线程同时编辑这些值,事情就会变得异常。每个线程都希望使用服务器提供的方法。既然数据不能在一个类的方法和另一个类的方法之间交换,那么最好的方法是什么?你知道吗


Tags: the方法fromimportip服务器client信息