我正在使用线程创建套接字服务器,但是在与每个线程进行交互时遇到问题。
示例:
假设3个客户端成功连接到服务器。现在,如何根据线程ID或线程号将数据发送到特定客户端?
到目前为止,我已经尝试过:
mydata = threading.local
mydata.x = number
,并且每次创建新线程时我都会增加数量,但是我只想将data.send(“ hello”)用于线程号3或线程号2或任何线程号。但是我什至无法获得线程号并进行管理。
def threaded(c, thread_num):
mydata = threading.local()
mydata.x = thread_num
while True:
data = c.recv(1024)
if not data:
break
def Main(myPort=None):
host = ''
thread_num = 0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, myPort))
print "\n"
print blue + "[*]" + reset +" Socket binded on port %s" % red + str(myPort) + reset
s.listen(5)
print blue + "[*]" + reset +" Listening for connection"
while True:
try:
c, addr = s.accept()
thread_num += 1
print(orange + "[*] " + reset + 'Connected to : IP: %s Port: %s ' % (red + str(addr[0])+ reset, red + str(addr[1])+ reset))
conn_data = {'IP':str(addr[0]), 'PORT':str(addr[1])}
start_new_thread(threaded, (c,thread_num))
except KeyboardInterrupt:
print red + "[!]" + reset + " Going to main menu"
break
s.close()
if __name__ == '__main__':
Main(8888)