Python Socket示例 本文共有7814个字,关键词: 1、单线程视频 2、TCP发送文件 3、UDP发送文件 1、单线程视频 Server端 import numpy, cv2,socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) addr = (socket.gethostname(), 8081) s.bind(addr) s.setblocking(0) # 非阻塞模式 while True: data = None try: data, _ = s.recvfrom(921600) if data: rec_data = numpy.frombuffer(data, dtype='uint8') r_img = cv2.imdecode(rec_data, 1) cv2.putText(r_img, "server", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2) cv2.imshow('server', r_img) except BlockingIOError as e: #print('error---->' + str(e)) pass if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.destroyAllWindows() Client端 import cv2,socket addr = (socket.gethostname(), 8081) cap = cv2.VideoCapture(0) #width and height cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) while True: _, img = cap.read() img = cv2.flip(img, 1) # 压缩图片 _, s_data = cv2.imencode('.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 50]) s.sendto(s_data, addr) print(f'sending,大小:{img.size} Byte') cv2.putText(img, "client", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2) cv2.imshow('client', img) if cv2.waitKey(1) & 0xFF == ord('q'): break s.close() cv2.destroyAllWindows() TCP发送文件(线程接收、支持命令、数据、文本) Server端 import datetime import socket, threading, time, os SIZE = 1024 # 存放图片的地址 filePath = '/home/bs/图片' def checkExsit(f_name): full_name = os.path.join(filePath, f_name) if os.path.exists(full_name): os.remove(full_name) print('Create file ...') with open(full_name, 'wb') as f: pass def recvImage(sock, f_name): while True: data = sock.recv(SIZE) if not data: break else: with open(os.path.join(filePath, f_name), 'ab') as f: f.write(data) print('data received') def saveImage(sock, f_type): print('Begin to save image ...') f_name = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f") + '.' + f_type checkExsit(f_name) t = threading.Thread(target=recvImage, args=(sock, f_name)) t.start() t.join() print('Finished saving image ...') def tcplink(sock, addr): print(f'Accept new connection from {addr}') # 发送问候信息(客户端接收到后返回一个'hello server') sock.send('hello'.encode('utf-8')) print((sock.recv(SIZE)).decode('utf-8')) print('Communication test success') while True: recv = (sock.recv(SIZE)).decode('utf-8') if recv: # 接收命令 if recv == 'c': print('receive command') cmd = (sock.recv(SIZE)).decode('utf-8') print(f'recv:{cmd}') sock.send(f'you have send command:-->{cmd}'.encode('utf-8')) # 判断命令并执行相应的程序 # 接收文件-自动识别文件类型 elif recv.split('-', 1)[0] == 'f': print('file command') saveImage(sock, recv.split('-', 1)[1]) else: print('receive other message -->' + recv) sock.send(f'you have send message:-->{recv}'.encode('utf-8')) recv = None def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('127.0.0.1', 9999)) s.listen(1) print('Waiting for connection...') while True: sock, addr = s.accept() t = threading.Thread(target=tcplink, args=(sock, addr)) t.start() if __name__ == '__main__': main() Client端 import socket, time def tcpclient(): SIZE = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 9999)) print('get from server -->' + (s.recv(SIZE)).decode('utf-8')) s.send('hello'.encode('utf-8')) time.sleep(0.5) print('command test begins ...') s.send('c'.encode('utf-8')) time.sleep(0.5) s.send('go shopping'.encode('utf-8')) print('get from server -->' + (s.recv(SIZE)).decode('utf-8')) print('command test ended') time.sleep(0.5) print('other msg test begins ...') s.send('I want to go outside!!!!'.encode('utf-8')) print('get from server -->' + (s.recv(SIZE)).decode('utf-8')) print('other msg test ended') time.sleep(0.5) send_f_name = '/home/bs/下载/1.jpeg' #将文件类型传输过去 f_ext = send_f_name.split('.')[-1] print('image test begins ...') s.send(('f-' + f_ext).encode('utf-8')) time.sleep(0.2) with open(send_f_name, 'rb') as f: for data in f: s.send(data) print('image test ended') s.close() print('connection closed') if __name__=='__main__': tcpclient() UDP传输文件 Server import socket count = 0 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_addr = ('127.0.0.1',9999) s.bind(server_addr) print('Bind UDP on 9999...') while True: if count == 0: data,client_addr = s.recvfrom(1024) print('connected from %s:%s'%client_addr) f = open(data, 'wb') data, client_addr = s.recvfrom(1024) if str(data) != "b'end'": f.write(data) print('recieved '+str(count)+' byte') else: break s.sendto('ok'.encode('utf-8'),client_addr) count+=1 print('recercled'+str(count)) f.close() s.close() Client import socket import os import time def Get_FilePath_FileName_FileExt(filename): filepath, tempfilename = os.path.split(filename) shotname, extension = os.path.splitext(tempfilename) return filepath, shotname, extension s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) filename = input('please enter the filename you want to send:\n') filepath, shotname, extension = Get_FilePath_FileName_FileExt(filename) client_addr = ('127.0.0.1',9999) f = open(filename,'rb') count = 0 flag = 1 while True: if count == 0: data = bytes(shotname+extension, encoding = "utf8") start = time.time() s.sendto(data,client_addr) data = f.read(1024) if str(data) != "b''": s.sendto(data,client_addr) print(str(count)+'byte') else: s.sendto('end'.encode('utf-8'),client_addr) break data, server_addr = s.recvfrom(1024) count+=1 print('recircled'+str(count)) s.close end = time.time() 「一键投喂 软糖/蛋糕/布丁/牛奶/冰阔乐!」 赞赏 × 梦白沙 (๑>ڡ<)☆谢谢老板~ 1元 2元 5元 10元 50元 任意金额 2元 使用微信扫描二维码完成支付 版权声明:本文为作者原创,如需转载须联系作者本人同意,未经作者本人同意不得擅自转载。 Python 2022-04-25 评论 290 次浏览