python achieved under the same local area network to transfer pictures

Python can be transmitted through the network socket picture, this is quite interesting.

The following use TCP to achieve for Python3.

Code Function Description

  • Send realized on a computer graphics (Sender)
  • Achieved in another computer (or may be different port on the same computer) accepts Pictures (Reciever)
  • Hair only once, and then only charge once
  • New images will be more a "new_" prefix on the old picture
  • The recipient must first open the code for the job after the restart sender Code (otherwise the sender of the code will be directly rejected)
  • The following are fixed on a computer (see ip address, write below is 127.0.0.1, if the other computer to write ip address on other computers)
  • In addition the program can only be used under the same local area network (even over the WAN, it is necessary to use the ip address WAN)

Code

Sender.py (sender):

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()

Reciever.py (recipients):

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()

Resolve

Sender Code: create a TCP socket, and initiate a connection.

Specific code as follows:

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 the next cycle, it starts to send pictures.

Packaged by struct library, and then use sockets to send

Note: Some code on the network is not directly used, such as here, it is necessary to become bytes str

To get the name of the file by the basic os library (this is to avoid some of the documents contained in the specific path)

Acquired file size by os library (described with respect to the acquired file size by state)

fhead = struct.pack(b'128sl', bytes(os.path.basename(filepath), encoding='utf-8'), os.stat(filepath).st_size)
s.send(fhead)

After again to get the files in binary mode.

Then sent, each fixed length data transmission. Read first, and then determines whether the air, and then transmitted.

* Receiving end: *

Still the same, to create a socket (but this needs to bind corresponding ip and port) to write specific code is as follows :( here is the listening socket object 10, but did not use in our code)

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)

After it enters into circulation, to determine whether the object sock to get here will enter the blocked state.

In the deal_data begin obtaining data via the connection objects.

Like, or an infinite loop, but in fact essentially empty, nothing special.

After that is passed over for the file name to handle it, here's the "128sl", it is actually a size scale (similar to the package size of the box the way). Then it is to get a new file name.

Corresponding code is as follows:

filename, filesize = struct.unpack('128sl', buf)
fn = filename.decode().strip('\x00')
new_filename = os.path.join('./', 'new_' + fn)
之后的recvd_size,其实就是为了来计数的标签。 

After we continue to receive, receiving while writing to the file until after have ended. To close off the corresponding file stream.

Finally, the socket is closed, exit the loop.

Wen source network for study purposes, if infringement contact deleted.

Published 38 original articles · won praise 1 · views 2179

Guess you like

Origin blog.csdn.net/wulishinian/article/details/105009912