socket通信
1.简单的套接字通信
1 import socket 2 phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 3 phone.bind(('127.0.0.1',8080)) 4 phone.listen(5) 5 print('starting...') 6 conn,client_addr = phone.accept() 7 data = conn.recv(1024) 8 conn.send(data.upper()) 9 conn.close() 10 phone.close()
1 import socket 2 phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 3 phone.connect(('127.0.0.1',8080)) 4 phone.send('hello'.encode('utf-8')) 5 data = phone.recv(1024) 6 print(data)
2.加上通信循环
1 import socket 2 phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 3 phone.bind(('127.0.0.1',8080)) 4 phone.listen(5) 5 print('starting...') 6 conn,client_addr = phone.accept() 7 while True: 8 data = conn.recv(1024) 9 print('%s 客户端发的数据'%str(client_addr),data) 10 conn.send(data.upper()) 11 conn.close() 12 phone.close()
1 import socket 2 phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 3 phone.connect(('127.0.0.1',8080)) 4 while True: 5 msg = input('msg>>>:').strip() 6 phone.send(msg.encode('utf-8')) 7 data = phone.recv(1024) 8 print('服务端返回的数据:',data) 9 phone.close()
3.bug 修复
1 import socket 2 phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 3 #如果遇到:Address already in use,需要socket配置,重用ip和端口,这里适合windows 4 phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) 5 phone.bind(('127.0.0.1',8080)) 6 phone.listen(5) 7 print('starting...') 8 conn,client_addr = phone.accept() 9 while True: 10 try: # client断开,这里适合windows 11 data = conn.recv(1024) 12 if not data:break # client断开,这里适合linux 13 print(data) 14 conn.send(data.upper()) 15 except ConnectionResetError as e: 16 print(e) 17 break 18 conn.close() 19 phone.close()
1 import socket 2 phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 3 phone.connect(('127.0.0.1',8080)) 4 while True: 5 msg = input('msg>>>:').strip() 6 if not msg: continue # 不能发 '' 空 数据 因为数据传给了 os os收到空 不会处理传到server端 7 phone.send(msg.encode('utf-8')) # 发送数据 将str型转成bytes型 8 data = phone.recv(1024) 9 print(data.decode('utf-8')) # 收数据 将bytes型转成str型 10 phone.close()
4.加上链接循环
1 import socket 2 phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 3 phone.bind(('127.0.0.1',8080)) 4 phone.listen(5) 5 print('starting...') 6 while True: 7 conn,client_addr = phone.accept() 8 while True: 9 try: 10 data = conn.recv(1024) 11 if not data:break 12 print('%s 的数据'%str(client_addr),data) 13 conn.send(data.upper()) 14 except ConnectionResetError as e: 15 # print(e) 16 break 17 conn.close() 18 phone.close()
1 import socket 2 phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 3 phone.connect(('127.0.0.1',8080)) 4 while True: 5 msg = input("msg>>>:").strip() 6 if not msg:continue 7 phone.send(msg.encode('utf-8')) 8 data = phone.recv(1024) 9 print(data.decode('utf-8')) 10 phone.close()
5.模拟ssh远程执行命令
1 import subprocess 2 obj = subprocess.Popen('dir d:',shell=True, 3 stdout=subprocess.PIPE, # 正确的结果 4 stderr=subprocess.PIPE) # 错误的结果 5 6 print('1:',obj.stdout.read().decode('gbk')) 7 print('2:',obj.stderr.read()) 8 9 import socket 10 import subprocess 11 phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 12 phone.bind(('127.0.0.1',8080)) 13 phone.listen(5) 14 print('starting...') 15 while True: 16 conn,client_addr = phone.accept() 17 print(client_addr) 18 while True: 19 try: 20 cmd = conn.recv(1024) 21 if not cmd: break 22 print(cmd) 23 obj = subprocess.Popen(cmd.decode('utf-8'),shell=True, 24 stdout=subprocess.PIPE, 25 stderr=subprocess.PIPE) 26 stdout = obj.stdout.read() 27 stderr = obj.stderr.read() 28 29 print(len(stdout)+len(stderr)) 30 31 conn.send(stdout) 32 conn.send(stderr) # 这样写比两个加起来 效率高 因为底层粘包不会影响 若是加起来就会新开一块内存 33 except ConnectionResetError as e: 34 break 35 conn.close() 36 37 phone.close()
1 import socket 2 phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 3 phone.connect(('127.0.0.1',8080)) 4 while True: 5 cmd = input('cmd>>>:').strip() 6 if not cmd:continue # 一定要写 不允许发空 7 phone.send(cmd.encode('utf-8')) 8 data = phone.recv(1024) # 这里如果收到的数据 > 1024 就发生了粘包 9 print(len(data)) 10 print(data.decode('gbk')) # linux 是gbk windows是utf-8 11 12 phone.close()
粘包
6.粘包
1 # 数据量比较小 时间比较短 才会发生粘包 2 # 解决粘包的办法: 3 # 明确知道对方给我发的包的长度 4 5 import socket 6 server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 7 server.bind(('127.0.0.1',8080)) 8 server.listen(5) 9 conn,client_addr = server.accept() 10 res1 = conn.recv(3) 11 print(res1.decode('utf-8')) 12 res2 = conn.recv(3) 13 print(res2) 14 res3 = conn.recv(10) 15 print(res3) 16 17 print(len('我们'.encode('utf-8'))) # len() 中文表示的是字符的长度 转成bytes型 len() 表示字节长度
1 # send recv 不是一一对应,一发可以多收,一收可以多发 2 import socket 3 client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 4 client.connect(('127.0.0.1',8080)) 5 client.send('我们'.encode('utf-8')) 6 client.send(b'hello') 7 client.send(b'world')
7.解决粘包 简单版
1 # struct模块 介绍 2 import struct 3 import json 4 # struct 模块可以将很长的一个数字压缩成4位 5 # i 有限的 若数字过大,会报错 6 # q Q d 是8位 i l L 是4位 d 不会报错 7 8 res = struct.pack('i',23213123) 9 print(res,len(res),type(res)) 10 # b'C4bx01' 4 <class 'bytes'> 11 data = struct.unpack('i',res) 12 print(data) 13 # (23213123,) 14 15 header_dic = { 16 'filename': 'a.txt', 17 'md5': '我们', 18 'total_size':1231142342342342323423432423234234 19 } 20 header_json = json.dumps(header_dic) 21 print(len(header_json.encode('utf-8'))) 22 header_bytes = header_json.encode('utf-8') 23 res = struct.pack('i',len(header_bytes)) 24 print(res,len(res)) 25 data = struct.unpack('i',res) 26 print(data)
1 import socket 2 import subprocess 3 import struct 4 server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 5 server.bind(('127.0.0.1',8080)) 6 server.listen(5) 7 print('starting...') 8 while True: 9 conn,client_addr = server.accept() 10 print(client_addr) 11 while True: 12 try: 13 cmd = conn.recv(1024) 14 if not cmd:continue 15 print(cmd) 16 obj = subprocess.Popen(cmd.decode('utf-8'),shell=True, 17 stdout=subprocess.PIPE, 18 stderr=subprocess.PIPE) 19 stdout = obj.stdout.read() 20 stderr = obj.stderr.read() 21 total_size = len(stdout) + len(stderr) 22 23 print(total_size) 24 header = struct.pack('i',total_size) 25 conn.send(header) 26 conn.send(stdout) 27 conn.send(stderr) 28 except ConnectionResetError as e: 29 # print(e) 30 break 31 conn.close() 32 33 server.close()
1 import socket 2 import struct 3 client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 4 client.connect(('127.0.0.1',8080)) 5 while True: 6 cmd = input('>>>:').strip() 7 if not cmd: continue 8 client.send(cmd.encode('utf-8')) 9 obj = client.recv(4) 10 total_size = struct.unpack('i',obj)[0] 11 12 # recv_data = client.recv(total_size) # 不能这样做 因为total_size 很可能很大, 13 # 有关部门建议的不要超过8192,再大反而会出现影响收发速度和不稳定的情况 14 recv_size = 0 15 recv_data = b'' # 这里不能写 None 16 while recv_size < total_size: 17 res = client.recv(1024) 18 recv_data += res 19 recv_size += len(res) 20 21 print(recv_data.decode('gbk')) # linux 是utf-8 windows 是gbk 22 23 client.close()
8.解决粘包 终极版
1 import socket 2 import subprocess 3 import struct 4 import pickle 5 6 server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 7 server.bind(('127.0.0.1',8080)) 8 server.listen(5) 9 print('starting...') 10 while True: 11 conn,client_addr = server.accept() 12 print(client_addr) 13 while True: 14 try: 15 cmd = conn.recv(1024) 16 if not cmd:continue 17 obj = subprocess.Popen(cmd.decode('utf-8'),shell=True, 18 stdout=subprocess.PIPE, 19 stderr=subprocess.PIPE) 20 stdout = obj.stdout.read() 21 stderr = obj.stderr.read() 22 total_size = len(stdout) + len(stderr) 23 24 header_dic = { 25 'filename':'a.txt', 26 'md5': 'xxxxxx', 27 'total_size':total_size 28 } 29 header_bytes = pickle.dumps(header_dic) 30 conn.send(struct.pack('i',len(header_bytes))) 31 conn.send(header_bytes) 32 conn.send(stdout) 33 conn.send(stderr) 34 35 except ConnectionResetError: 36 break 37 conn.close() 38 39 server.close()
1 import socket 2 import struct 3 import pickle 4 client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 5 client.connect(('127.0.0.1',8080)) 6 while True: 7 cmd = input('>>>:').strip() 8 if not cmd: continue 9 client.send(cmd.encode('utf-8')) 10 header = client.recv(4) 11 header_size = struct.unpack('i',header)[0] 12 header_bytes = client.recv(header_size) 13 header_dic = pickle.loads(header_bytes) 14 print(header_dic) 15 total_size = header_dic['total_size'] 16 17 recv_size = 0 18 recv_data = b'' 19 while recv_size < total_size: 20 res = client.recv(1024) 21 recv_data += res 22 recv_size += len(res) 23 print(recv_data.decode('gbk')) 24 25 client.close()
文件传输
9.文件传输 简单版
1 import socket 2 import os 3 import struct 4 import pickle 5 6 dirname = os.path.dirname(os.path.abspath(__file__)) 7 filepath = os.path.join(dirname,'share') 8 9 server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 10 server.bind(('127.0.0.1',8080)) 11 server.listen(5) 12 print('starting...') 13 while True: 14 conn,client_addr = server.accept() 15 print(client_addr) 16 while True: 17 try: 18 res = conn.recv(1024) 19 if not res:continue 20 cmds = res.decode('utf-8').split() 21 filename = cmds[1] 22 23 file_path = os.path.join(filepath,filename) 24 if os.path.isfile(file_path): 25 header = { 26 'filename': filename, 27 'md5': 'xxxxxx', 28 'file_size': os.path.getsize(file_path) 29 } 30 header_bytes = pickle.dumps(header) 31 conn.send(struct.pack('i',len(header_bytes))) 32 conn.send(header_bytes) 33 34 with open(file_path,'rb') as f: 35 for line in f: 36 conn.send(line) 37 else: 38 conn.send(struct.pack('i',0)) 39 except ConnectionResetError: 40 break 41 conn.close() 42 43 server.close()
1 import socket 2 import struct 3 import pickle 4 import os 5 6 dirname = os.path.dirname(os.path.abspath(__file__)) 7 filepath = os.path.join(dirname,'download') 8 9 client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 10 client.connect(('127.0.0.1',8080)) 11 while True: 12 msg = input(">>>:").strip() # get a.txt 13 if not msg:continue 14 client.send(msg.encode('utf-8')) 15 obj = client.recv(4) 16 header_size = struct.unpack('i',obj)[0] 17 if header_size == 0: 18 print('文件不存在') 19 else: 20 header_types = client.recv(header_size) 21 header_dic = pickle.loads(header_types) 22 print(header_dic) 23 file_size = header_dic['file_size'] 24 filename = header_dic['filename'] 25 26 with open('%s/%s' % (filepath, filename), 'wb') as f: 27 recv_size = 0 28 while recv_size < file_size: 29 res = client.recv(1024) 30 f.write(res) 31 recv_size += len(res) 32 print('总大小:%s 已下载:%s'%(file_size,recv_size)) 33 34 client.close()
10.文件传输 优化版
1 import socket 2 import os 3 import struct 4 import pickle 5 6 dirname = os.path.dirname(os.path.abspath(__file__)) 7 filepath = os.path.join(dirname, 'share') 8 9 10 def get(cmds,conn): 11 filename = cmds[1] 12 file_path = os.path.join(filepath, filename) 13 if os.path.isfile(file_path): 14 header = { 15 'filename': filename, 16 'md5': 'xxxxxx', 17 'file_size': os.path.getsize(file_path) 18 } 19 header_bytes = pickle.dumps(header) 20 conn.send(struct.pack('i', len(header_bytes))) 21 conn.send(header_bytes) 22 23 with open(file_path, 'rb') as f: 24 for line in f: 25 conn.send(line) 26 else: 27 conn.send(struct.pack('i', 0)) 28 29 30 def put(cmds,conn): 31 pass 32 33 34 def run(): 35 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 36 server.bind(('127.0.0.1', 8080)) 37 server.listen(5) 38 print('starting...') 39 while True: 40 conn, client_addr = server.accept() 41 print(client_addr) 42 while True: 43 try: 44 res = conn.recv(1024) 45 if not res: continue 46 cmds = res.decode('utf-8').split() 47 if cmds[0] == 'get': 48 get(cmds,conn) 49 elif cmds[0] == 'put': 50 put(cmds,conn) 51 except ConnectionResetError: 52 break 53 conn.close() 54 55 server.close() 56 57 58 if __name__ == '__main__': 59 run()
1 import socket 2 import struct 3 import pickle 4 import os 5 6 dirname = os.path.dirname(os.path.abspath(__file__)) 7 filepath = os.path.join(dirname,'download') 8 9 10 def get(client): 11 obj = client.recv(4) 12 header_size = struct.unpack('i', obj)[0] 13 if header_size == 0: 14 print('文件不存在') 15 else: 16 header_types = client.recv(header_size) 17 header_dic = pickle.loads(header_types) 18 print(header_dic) 19 file_size = header_dic['file_size'] 20 filename = header_dic['filename'] 21 22 with open('%s/%s' % (filepath, filename), 'wb') as f: 23 recv_size = 0 24 while recv_size < file_size: 25 res = client.recv(1024) 26 f.write(res) 27 recv_size += len(res) 28 print('总大小:%s 已下载:%s' % (file_size, recv_size)) 29 30 31 def put(): 32 pass 33 34 35 def run(): 36 client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 37 client.connect(('127.0.0.1',8080)) 38 while True: 39 msg = input(">>>:").strip() # get a.txt 40 if not msg:continue 41 client.send(msg.encode('utf-8')) 42 43 cmds = msg.split() 44 if cmds[0] == 'get': 45 get(client) 46 elif cmds[0] == 'put': 47 put() 48 49 client.close() 50 51 52 if __name__ == '__main__': 53 run()
11.文件传输 面向对象版本
1 import socket 2 import os 3 import struct 4 import pickle 5 6 7 class TCPServer: 8 address_family = socket.AF_INET 9 socket_type = socket.SOCK_STREAM 10 listen_count = 5 11 max_recv_bytes = 8192 12 coding = 'utf-8' 13 allow_reuse_address = False 14 # 下载的文件存放路径 15 down_filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'share') 16 # 上传的文件存放路径 17 upload_filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'upload') 18 19 def __init__(self,server_address,bind_and_listen=True): 20 self.server_address = server_address 21 self.socket = socket.socket(self.address_family,self.socket_type) 22 23 if bind_and_listen: 24 try: 25 self.server_bind() 26 self.server_listen() 27 except Exception: 28 self.server_close() 29 30 def server_bind(self): 31 if self.allow_reuse_address: 32 self.socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) 33 self.socket.bind(self.server_address) 34 35 def server_listen(self): 36 self.socket.listen(self.listen_count) 37 38 def server_close(self): 39 self.socket.close() 40 41 def server_accept(self): 42 return self.socket.accept() 43 44 def conn_close(self,conn): 45 conn.close() 46 47 def run(self): 48 print('starting...') 49 while True: 50 self.conn,self.client_addr = self.server_accept() 51 print(self.client_addr) 52 while True: 53 try: 54 res = self.conn.recv(self.max_recv_bytes) 55 if not res:continue 56 cmds = res.decode(self.coding).split() 57 if hasattr(self,cmds[0]): 58 func = getattr(self,cmds[0]) 59 func(cmds) 60 except Exception: 61 break 62 self.conn_close(self.conn) 63 64 def get(self,cmds): 65 """ 下载 66 1.找到下载的文件 67 2.发送 header_size 68 3.发送 header_bytes file_size 69 4.读文件 rb 发送 send(line) 70 5.若文件不存在,发送0 client提示:文件不存在 71 :param cmds: 下载的文件 eg:['get','a.txt'] 72 :return: 73 """ 74 filename = cmds[1] 75 file_path = os.path.join(self.down_filepath, filename) 76 if os.path.isfile(file_path): 77 header = { 78 'filename': filename, 79 'md5': 'xxxxxx', 80 'file_size': os.path.getsize(file_path) 81 } 82 header_bytes = pickle.dumps(header) 83 self.conn.send(struct.pack('i', len(header_bytes))) 84 self.conn.send(header_bytes) 85 with open(file_path, 'rb') as f: 86 for line in f: 87 self.conn.send(line) 88 else: 89 self.conn.send(struct.pack('i', 0)) 90 91 def put(self,cmds): 92 """ 上传 93 1.接收4个bytes 得到文件的 header_size 94 2.根据 header_size 得到 header_bytes header_dic 95 3.根据 header_dic 得到 file_size 96 3.以写的形式 打开文件 f.write() 97 :param cmds: 下载的文件 eg:['put','a.txt'] 98 :return: 99 """ 100 obj = self.conn.recv(4) 101 header_size = struct.unpack('i', obj)[0] 102 header_bytes = self.conn.recv(header_size) 103 header_dic = pickle.loads(header_bytes) 104 print(header_dic) 105 file_size = header_dic['file_size'] 106 filename = header_dic['filename'] 107 108 with open('%s/%s' % (self.upload_filepath, filename), 'wb') as f: 109 recv_size = 0 110 while recv_size < file_size: 111 res = self.conn.recv(self.max_recv_bytes) 112 f.write(res) 113 recv_size += len(res) 114 115 116 tcp_server = TCPServer(('127.0.0.1',8080)) 117 tcp_server.run() 118 tcp_server.server_close()
1 import socket 2 import struct 3 import pickle 4 import os 5 6 7 class FTPClient: 8 address_family = socket.AF_INET 9 socket_type = socket.SOCK_STREAM 10 # 下载的文件存放路径 11 down_filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'download') 12 # 上传的文件存放路径 13 upload_filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'share') 14 coding = 'utf-8' 15 max_recv_bytes = 8192 16 17 def __init__(self, server_address, connect=True): 18 self.server_address = server_address 19 self.socket = socket.socket(self.address_family, self.socket_type) 20 if connect: 21 try: 22 self.client_connect() 23 except Exception: 24 self.client_close() 25 26 def client_connect(self): 27 self.socket.connect(self.server_address) 28 29 def client_close(self): 30 self.socket.close() 31 32 def run(self): 33 while True: 34 # get a.txt 下载 put a.txt 上传 35 msg = input(">>>:").strip() 36 if not msg: continue 37 self.socket.send(msg.encode(self.coding)) 38 cmds = msg.split() 39 if hasattr(self,cmds[0]): 40 func = getattr(self,cmds[0]) 41 func(cmds) 42 43 def get(self, cmds): 44 """ 下载 45 1.得到 header_size 46 2.得到 header_types header_dic 47 3.得到 file_size file_name 48 4.以写的形式 打开文件 49 :param cmds: 下载的内容 eg: cmds = ['get','a.txt'] 50 :return: 51 """ 52 obj = self.socket.recv(4) 53 header_size = struct.unpack('i', obj)[0] 54 if header_size == 0: 55 print('文件不存在') 56 else: 57 header_types = self.socket.recv(header_size) 58 header_dic = pickle.loads(header_types) 59 print(header_dic) 60 file_size = header_dic['file_size'] 61 filename = header_dic['filename'] 62 63 with open('%s/%s' % (self.down_filepath, filename), 'wb') as f: 64 recv_size = 0 65 while recv_size < file_size: 66 res = self.socket.recv(self.max_recv_bytes) 67 f.write(res) 68 recv_size += len(res) 69 print('总大小:%s 已下载:%s' % (file_size, recv_size)) 70 else: 71 print('下载成功!') 72 73 def put(self, cmds): 74 """ 上传 75 1.查看上传的文件是否存在 76 2.上传文件 header_size 77 3.上传文件 header_bytes 78 4.以读的形式 打开文件 send(line) 79 :param cmds: 上传的内容 eg: cmds = ['put','a.txt'] 80 :return: 81 """ 82 filename = cmds[1] 83 file_path = os.path.join(self.upload_filepath, filename) 84 if os.path.isfile(file_path): 85 file_size = os.path.getsize(file_path) 86 header = { 87 'filename': os.path.basename(filename), 88 'md5': 'xxxxxx', 89 'file_size': file_size 90 } 91 header_bytes = pickle.dumps(header) 92 self.socket.send(struct.pack('i', len(header_bytes))) 93 self.socket.send(header_bytes) 94 95 with open(file_path, 'rb') as f: 96 send_bytes = b'' 97 for line in f: 98 self.socket.send(line) 99 send_bytes += line 100 print('总大小:%s 已上传:%s' % (file_size, len(send_bytes))) 101 else: 102 print('上传成功!') 103 else: 104 print('文件不存在') 105 106 107 ftp_client = FTPClient(('127.0.0.1',8080)) 108 ftp_client.run() 109 ftp_client.client_close()
UDP
12.UDP协议 简单版
1 import socket 2 server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 3 server.bind(('127.0.0.1',8080)) 4 while True: 5 data,client_addr = server.recvfrom(1024) 6 print('客户端数据:',data) 7 server.sendto(data.upper(),client_addr)
1 import socket 2 client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 3 while True: 4 msg = input('>>>:').strip() 5 client.sendto(msg.encode('utf-8'),('127.0.0.1',8080)) 6 data,server_addr =client.recvfrom(10224) 7 print(data,server_addr)
13.UDP协议 不会粘包
1 import socket 2 server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 3 server.bind(('127.0.0.1',8080)) 4 res1 = server.recvfrom(5) 5 print(res1) 6 res2 = server.recvfrom(1024) 7 print(res2) 8 server.close()
1 import socket 2 client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 3 client.sendto(b'hello',('127.0.0.1',8080)) 4 client.sendto(b'world',('127.0.0.1',8080)) 5 client.close()
14.UDP 执行指令查看服务端的时间,设置时间同步
1 import socket 2 import subprocess 3 import time 4 server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 5 server.bind(('127.0.0.1',8080)) 6 while True: 7 data,client_addr = server.recvfrom(1024) 8 print(data,client_addr) 9 # obj = subprocess.Popen(data.decode('utf-8'),shell=True, # time 命令在windows 下不能用 10 # stdout=subprocess.PIPE, 11 # stderr=subprocess.PIPE) 12 # stdout = obj.stdout.read() 13 # stderr = obj.stderr.read() 14 # print(stdout+stderr) 15 # server.sendto(stdout+stderr,client_addr) 16 if data.decode('utf-8') == 'time': 17 str_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()) 18 # str_time = '2017-01-01 00:00:00' 19 server.sendto(str_time.encode('gbk'),client_addr) 20 21 server.close()
1 import socket 2 import os 3 import time 4 client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 5 while True: 6 msg = input('>>>:').strip() 7 client.sendto(msg.encode('utf-8'),('127.0.0.1',8080)) 8 data,server_addr = client.recvfrom(1024) 9 print(data.decode('utf-8'),server_addr) 10 # localtime = time.localtime() 11 # os.system("date %d-%d-%d" % (localtime.tm_year, localtime.tm_mon, localtime.tm_mday)) # 设置日期 12 # os.system("time %d:%d:%d.0" % (localtime.tm_hour, localtime.tm_min, localtime.tm_sec)) # 设置时间 13 14 client.close()