1、server端
支持多客户端连接。
1 #!/usr/bin/python3 2 3 import socket 4 from threading import Thread 5 import time 6 from multiprocessing import Process 7 import subprocess 8 9 10 host = '192.168.10.40' 11 port = 9999 12 ADDRESS = (host,port) 13 14 g_socket_server = None # 负责监听的socket 15 g_conn_pool = {} # 连接池 16 def init(): 17 """ 18 初始化服务端 19 """ 20 global g_socket_server 21 g_socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 22 g_socket_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 23 g_socket_server.bind(ADDRESS) 24 g_socket_server.listen(5) # 最大等待数(有很多人误以为最大连接数) 25 print("Server start, wait for client connecting...") 26 27 def accept_client(): 28 """ 29 接收新连接 30 """ 31 while True: 32 client, address = g_socket_server.accept() # 阻塞,等待客户端连接 33 # 给每个客户端创建一个独立的线程进行管理 34 thread = Thread(target=message_handle, args=(client,address)) 35 # 设置成守护线程 36 thread.setDaemon(True) 37 thread.start() 38 39 def message_handle(client, address): 40 """ 41 消息处理 42 """ 43 address = str(address) 44 print("[+] Connected with: " , address) 45 client.sendall("Connect server successfully!".encode()) 46 g_conn_pool[address] = client 47 48 while True: 49 try: 50 bytes = client.recv(1024) 51 data = bytes.decode() 52 if "" == data: # client.close() 53 print("客户端主动退出连接") 54 remove_client(address) 55 break 56 57 print('[Received]', data) 58 result = run_command(data) 59 print('[Result]',result) 60 client.sendall(result.encode()) 61 except Exception as e: # close cmd terminal 62 print("客户端意外退出连接") 63 print(e) 64 remove_client(address) 65 break 66 67 68 def run_command(command): 69 result = None 70 result = subprocess.getoutput(command) 71 return result 72 73 def remove_client(address): 74 75 address = str(address) 76 client = g_conn_pool[address] 77 if None != client: 78 client.close() 79 g_conn_pool.pop(address) 80 print("client offline: " + address) 81 82 if __name__ == '__main__': 83 init() 84 # 新开一个线程,用于接受新连接 85 thread = Thread(target=accept_client) 86 thread.setDaemon(True) 87 thread.start() 88 # 主线程逻辑 89 while True: 90 time.sleep(0.1)
2、client端
客户端输入#exit后,主动退出连接
1 #!/usr/bin/python3 2 # 文件名:client.py 3 4 # 导入 socket、sys 模块 5 import socket 6 import sys 7 8 9 10 11 def new_client(): 12 # 创建 socket 对象 13 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 14 15 # 获取本地主机名 16 host = socket.gethostname() 17 host = '192.168.10.40' 18 19 # 设置端口号 20 port = 9999 21 try: 22 client.connect((host, port)) # 尝试进行连接 23 print(client.recv(1024).decode()) 24 except Exception: 25 print('[!]Server not found or not open') 26 sys.exit() 27 while True: 28 trigger = input('Input:') 29 if trigger == '#exit': # 自定义结束字符串 30 break 31 client.sendall(trigger.encode()) 32 data = client.recv(1024) # 接收小于 1024 字节的数据 33 data = data.decode() 34 print('[Received]',data) 35 36 client.close() 37 38 if __name__ == "__main__": 39 new_client()