在 Python 中识别线程

Identify Thread in Python

我有一个 python 套接字服务器 运行 和套接字客户端。

现在,假设有 3 个客户端连接到同一台服务器。请在下面找到服务器代码。

#!/usr/bin/python           # This is server.py file

import socket               # Import socket module
import threading

serversocket = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 1234                # Reserve a port for your service.
serversocket.bind((host, port))        # Bind to the port
serversocket.listen(5)
print("Bound the port ",port,"on Machine : ",host,", and ready to accept connections.\n")

def clientThread(connection):
    while True:
        data=connection.recv(1024)
        if not data:
            break
        connection.send("Thanks")

    connection.close()

def sendMessage(connection, message):
    connection.send(message)

while 1:
    connection, address = serversocket.accept()
    start_new_thread(clientthread, (connection,))

serversocket.close();

现在,我需要为特定客户端调用 sendMessage,比如从客户端 A、B 和 C 中将其发送到 B。在这种情况下,我如何识别线程并调用该函数?

您可以使用队列和每个连接的多个线程来解决这个问题。

基本概况:

  1. 每个客户端连接产生两个线程 - 一个用于监视客户端输入,另一个用于监视队列。放在队列中的项目将被发送到客户端。每个客户端连接都有自己的输出队列。

  2. 您还需要一个全局字典来将客户端名称映射到它们的输出队列。

  3. 要向特定客户端发送消息,找到客户端的输出队列并将消息添加到其中。

  4. 您还需要一种关闭客户端输出线程的方法。一种常见的方法是在队列上使用 sentinel 值(如 None)来通知输出线程退出其处理循环。当客户端的输入线程检测到 EOF 时,它可以将标记值放在客户端的输出队列中,最终输出线程将自行关闭。