我想在Python中構建一個TCP IP服務器。 我的目標是在客戶端上運行命令。 要運行命令,您必須在服務器中鍵入「cmd命令」。 我從來沒有與線程工作過,現在我似乎無法找到如何發送我想執行到客戶端線程的命令。 任何人都可以指向正確的方向嗎?如何向我的TCP IP服務器中的所有客戶端線程發送消息?
我迄今爲止代碼:
import socket
import sys
from thread import *
HOST = ''
PORT = 8884
clients = 0
connected_id = ""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
# Bind socket to local host and 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 successfully binded'
# Start listening on socket
s.listen(10)
print 'Socket is listening'
# Function for handling connections.
def clientthread(conn):
# Sending message to connected client
conn.sendall('hello') # send only takes string
global clients
# loop until disconnect
while True:
# Receiving from client
data = conn.recv(1024)
if data.lower().find("id=-1") != -1:
clients += 1
print("new client ID set to " + 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 as a function name to be run, second is the tuple of arguments to the function
conn, addr = sock.accept()
print('Client connected on ' + addr[0])
start_new_thread(clientthread, (conn,))
def sendallclients(message):
# send msg to all clients
tmp = 0
# now keep talking with the clients
start_new_thread(addclientsthread, (s,))
usr_input = ""
while str(usr_input) != "Q":
# do stuff
usr_input = raw_input("Enter 'Q' to quit")
if usr_input.find("cmd") == 0:
sendallclients(usr_input[3:])
if usr_input.find("hi") == 0:
sendallclients("hey")
s.close()
凡定義'start_new_thread'? –
@ t.m.adam它來自線程 – Newyork167
我的不好,我認爲這是你的功能。無論如何,正如@ Newyork167所說的那樣,製作一份「客戶」列表並添加新的客戶端。然後你可以遍歷該列表 –