Python TCP Socket Image Transfer: Sender and Receiver Implementation
This article demonstrates how to use Python 3 TCP sockets to send an image file from one computer to another, detailing the sender and receiver scripts, the required struct packing, file handling, and network considerations for successful transmission.
Python can transmit images over a network using sockets, and this guide provides a complete TCP‑based implementation suitable for Python 3.
Code functionality summary
Sender script sends an image file.
Receiver script receives the image and saves it with a new_ prefix.
Each side runs once; the sender must start after the receiver is listening.
Works on a single LAN (use appropriate IP addresses for different machines).
Sender (Sender.py)
import socket
import os
import sys
import struct
def sock_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)
print(sys.exit(1))
while True:
filepath = input('input the file: ')
# filepath = 'test.png'
fhead = struct.pack(b'128sl', bytes(os.path.basename(filepath), encoding='utf-8'), os.stat(filepath).st_size)
s.send(fhead)
print('client filepath: {0}'.format(filepath))
fp = open(filepath, 'rb')
while 1:
data = fp.read(1024)
if not data:
print('{0} file send over...'.format(filepath))
break
s.send(data)
s.close()
break
if __name__ == '__main__':
sock_client()The sender creates a TCP socket, connects to the receiver, packs the filename and size with struct.pack('128sl', ...), sends the header, then streams the file in 1024‑byte chunks.
Receiver (Receiver.py)
import socket
import os
import sys
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("Wait")
while True:
sock, addr = s.accept()
deal_data(sock, addr)
break
s.close()
def deal_data(sock, addr):
print("Accept connection from {0}".format(addr))
while True:
fileinfo_size = struct.calcsize('128sl')
buf = sock.recv(fileinfo_size)
if buf:
filename, filesize = struct.unpack('128sl', buf)
fn = filename.decode().strip('\x00')
new_filename = os.path.join('./', 'new_' + fn)
recvd_size = 0
fp = open(new_filename, 'wb')
while not recvd_size == filesize:
if filesize - recvd_size > 1024:
data = sock.recv(1024)
recvd_size += len(data)
else:
data = sock.recv(1024)
recvd_size = filesize
fp.write(data)
fp.close()
sock.close()
break
if __name__ == '__main__':
socket_service()The receiver binds to the same IP and port, listens for a connection, then in deal_data reads the header, reconstructs the filename, creates a new file prefixed with new_, and writes incoming data until the declared file size is reached.
Key points:
Both scripts use struct to pack/unpack a fixed‑size header ( '128sl').
The sender must be started after the receiver is listening, otherwise the connection is refused.
The implementation works within the same LAN; for WAN use the appropriate public IP.
© 文源网络,仅供学习之用,如有侵权,联系删除.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
