我试图在随机时间发送TCP消息,具体取决于收到用户输入的时间,发送给我从中接收每个客户端线程数据的多个客户端之一。
我将每个客户端的IP存储在SQL数据库中,我决定根据用户输入发送数据的IP。我该如何处理向特定客户发送消息?我不知道如何通过每个套接字连接访问并使用它来发送消息。
非常欢迎任何设备,示例链接或代码段。
这是我到目前为止的服务器代码:
import socket
import threading
from database import Database
d = Database()
def Read_RFID_tag():
while True:
receiveID = raw_input("tag input : ")
d.updateTable(receiveID, 1);
print(receiveID)
class ThreadedServer(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
def listen(self):
self.sock.listen(5)
while True:
client, address = self.sock.accept()
print("new client")
client.settimeout(60)
threading.Thread(target = self.listenToClient,args = (client,address)).start()
def listenToClient(self, client, address):
size = 1024
while True:
query_result = d.existsWashedInTable(address)
try:
data = client.recv(size)
if data:
# Set the response to echo back the received data
print(data)
response = data
d.addEntryToTable(response,address, 0)
client.send(response)
else:
raise error('Client disconnected')
except:
client.close()
return False
if __name__ == "__main__":
port_num = 5005
d.createTable()
threading.Thread(target=Read_RFID_tag).start()
ThreadedServer('',port_num).listen()