How do I send a message to all client threads in my TCP IP server in Python? -
i'm trying build tcp ip server in python. goal run commands on clients. run command you'll have type "cmd command" in server. i've never worked threads before , can't seem find out how send command want execute client threads. point me in right direction?
my code far:
import socket import sys thread import * host = '' port = 8884 clients = 0 connected_id = "" s = socket.socket(socket.af_inet, socket.sock_stream) print 'socket created' # bind socket local host , port try: s.bind((host, port)) except socket.error, msg: print 'bind failed. error code : ' + str(msg[0]) + ' message ' + msg[1] sys.exit() print 'socket binded' # start listening on socket s.listen(10) print 'socket listening' # function handling connections. def clientthread(conn): # sending message connected client conn.sendall('hello') # send takes string global clients # loop until disconnect while true: # receiving client data = conn.recv(1024) if data.lower().find("id=-1") != -1: clients += 1 print("new client id set " + str(clients)) conn.sendall("sid=" + str(clients)) if not data: break # if client disconnects conn.close() def addclientsthread(sock): # start new thread takes 1st argument function name run, second tuple of arguments function conn, addr = sock.accept() print('client connected on ' + addr[0]) start_new_thread(clientthread, (conn,)) def sendallclients(message): # send msg clients tmp = 0 # keep talking clients start_new_thread(addclientsthread, (s,)) usr_input = "" while str(usr_input) != "q": # stuff usr_input = raw_input("enter 'q' quit") if usr_input.find("cmd") == 0: sendallclients(usr_input[3:]) if usr_input.find("hi") == 0: sendallclients("hey") s.close()
first make clients list :
my_clients = []
then modify addclientsthread
add new clients list :
def addclientsthread(sock): global my_clients conn, addr = sock.accept() my_clients += [conn] print('client connected on ' + addr[0]) start_new_thread(clientthread, (conn,))
next iterate on my_clients
in sendallclients
function :
def sendallclients(message): client in my_clients : client.send(message)
now clients should receive message
Comments
Post a Comment