1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python socket传输图片

python socket传输图片

时间:2020-09-05 01:02:30

相关推荐

python socket传输图片

使用 socket 实现图片传输。

# -*- coding=utf-8 -*-"""file: recv.pysocket service"""import socketimport threadingimport timeimport sysimport osimport structdef socket_service():try:s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)s.bind(('127.0.0.1', 6666))s.listen(10)except socket.error as msg:print(msg)sys.exit(1)print('Waiting connection...')while 1:conn, addr = s.accept()t = threading.Thread(target=deal_data, args=(conn, addr))t.start()def deal_data(conn, addr):print('Accept new connection from {0}'.format(addr))#conn.settimeout(500)conn.send('Hi, Welcome to the server!'.encode("utf-8"))while 1:fileinfo_size = struct.calcsize('128sl')buf = conn.recv(fileinfo_size)if buf:filename, filesize = struct.unpack('128sl', buf)fn = filename.strip(b"\x00").decode("utf-8")new_filename = os.path.join('./', 'new_' + fn)print(new_filename,filesize)print('file new name is {0}, filesize if {1}'.format(new_filename,filesize))recvd_size = 0 # 定义已接收文件的大小fp = open(new_filename, 'wb')print('start receiving...')while not recvd_size == filesize:if filesize - recvd_size > 1024:data = conn.recv(1024)recvd_size += len(data)else:data = conn.recv(filesize - recvd_size)recvd_size = filesizefp.write(data)fp.close()print('end receive...')conn.send('已发送'.encode("utf-8"))print(conn.recv(1024).decode('utf-8'))conn.close()breakif __name__ == '__main__':socket_service()

# -*- coding=utf-8 -*-"""file: send.pysocket client"""import socketimport osimport sysimport structimport win32uiimport cv2capture = cv2.VideoCapture(0)def socket_client():try:s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect(('127.0.0.1', 6666))except socket.error as msg:print(msg)sys.exit(1)print(s.recv(1024).decode("utf-8"))while 1:#ret, frame = capture.read()#cv2.imwrite("C:/Users/***/Pictures/Saved Pictures/youtemp.jpg", frame)#capture.release() # 释放摄像头#cv2.destroyAllWindows()dlg = win32ui.CreateFileDialog(1) # 1表示打开文件对话框dlg.SetOFNInitialDir('C:/') # 设置打开文件对话框中的初始显示目录dlg.DoModal()filepath = dlg.GetPathName() # 获取选择的文件名称print(filepath)# filepath = input('please input file path: ')if os.path.isfile(filepath):# 定义定义文件信息。128s表示文件名为128bytes长,l表示一个int或log文件类型,在此为文件大小fileinfo_size = struct.calcsize('128sl')# 定义文件头信息,包含文件名和文件大小fhead = struct.pack('128sl',os.path.basename(filepath).encode(encoding="utf-8"),os.stat(filepath).st_size)print('client filepath: {0}'.format(filepath))s.send(fhead)fp = open(filepath, 'rb')while 1:data = fp.read(1024)if not data:print('{0} file send over...'.format(filepath))breaks.send(data)print(s.recv(1024).decode("utf-8"))print(s.recv(1024).decode("utf-8"))s.close()breakif __name__ == '__main__':socket_client()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。