python socket传输图片

2022-08-14 08:35:57

 使用 socket 实现图片传输。

# -*- coding=utf-8 -*-

"""
file: recv.py
socket service
"""
import socket
import threading
import time
import sys
import os
import struct


def 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 = filesize
                fp.write(data)
            fp.close()
            print('end receive...')
        conn.send('已发送'.encode("utf-8"))
        print(conn.recv(1024).decode('utf-8'))
        conn.close()
        break


if __name__ == '__main__':
    socket_service()
# -*- coding=utf-8 -*-

"""
file: send.py
socket client
"""

import socket
import os
import sys
import struct
import win32ui
import cv2
capture = 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))
					break
				s.send(data)
		print(s.recv(1024).decode("utf-8"))
		print(s.recv(1024).decode("utf-8"))
		s.close()
		break


if __name__ == '__main__':
    socket_client()
  • 作者:奇点.
  • 原文链接:https://blog.csdn.net/qq_37688204/article/details/100287513
    更新时间:2022-08-14 08:35:57