python socket

python版本3.7.0
使用socket的步骤:

  • server端
    • socket
    • bind
    • listen
    • accept
    • send&recv
  • client端
    • socket
    • connect
    • send&recv

实现一个文件传输功能
server端

'''sendfile.py'''
'''As server, send file to client.'''
'''LCL'''
import socket
import os
import time

host = socket.gethostbyname_ex(socket.gethostname())
print(host)
server = socket.socket()
saddr = host[-1][0]
port = 4523
server.bind((saddr,port))
server.listen(1)
print('Watting receiver connecting ...')
conn,caddr = server.accept()
print(caddr,' connected!')

filename = 'D:\Synthesia-10.1+Cracked.zip'
filesize = os.stat(filename).st_size
rep = input('Send {} {:.2f} K? [y/n] :'.format(filename,filesize/1024))
if rep=='y' or rep=='Y':
    conn.sendall(filename.encode('utf-8'))
    conn.sendall(filesize.to_bytes(4,'big'))    
    print('Waiting {} to confirm...'.format(caddr))
    rep = conn.recv(256).decode('utf-8')
    if rep=='y' or rep=='Y':
        print('{} is ready to receive.'.format(caddr))
        print('Sending...')
        f = open(filename,'rb')
        data = f.read()
        start = time.time()
        conn.sendall(data)
        end = time.time()
        print('Complete!')
        print('Using {:.2f} s'.format(end-start))
        f.close()
    else:
        print('{} reject to receive.'.format(caddr))
else:
    print('Send cancel.')
server.close()
        

client端

'''recvfile.py'''
'''As client, receive file from server.'''
'''LCL'''
import socket
import os
import time
import sys

def processbar(precent):  #进度条
    num = int(precent*20)
    s = '[ ' + '#'*num + '-'*(20-num) + ' ]'
    return s

client = socket.socket()
buffersize = 256 * 1024
recvsize = 0
servername = socket.gethostname()  #这里是因为用的同一台电脑收发,正常情况下应该给主机名
saddr = socket.gethostbyname(servername)#"10.250.245.23"
port = 4523
client.connect((saddr,port))
print('Connect success!')

recvname = client.recv(buffersize).decode('utf-8')
filename = recvname[recvname.rfind('\\')+1:]
path = 'D:\\recv\\'
filesize = int.from_bytes(client.recv(buffersize),'big')

rep = input('Receive {} {:.2f} K? [y/n]: '.format(filename,filesize/1024))
client.sendall(rep.encode('utf-8'))
if rep == 'y' or rep == 'Y':
    f = open(path+'new'+filename,'wb')
    start = time.time()
    while recvsize < filesize:
        if filesize-recvsize

运行效果如下

C:\Users\Administrator>python D:\Python37\sendfile.py
('THQKV8VN3GOSNY1', [], ['192.168.33.1', '192.168.220.1', '192.168.1.101'])
Watting receiver connecting ...
('192.168.33.1', 64012)  connected!
Send D:\Synthesia-10.1+Cracked.zip 4846.18 K? [y/n] :y
Waiting ('192.168.33.1', 64012) to confirm...
('192.168.33.1', 64012) is ready to receive.
sending...
Complete!
Using 0.01 s
 C:\Users\Administrator>python D:\Python37\recvfile.py
Connect success!
Receive Synthesia-10.1+Cracked.zip 4846.18 K? [y/n]: y
recv  [ #------------------- ] 256.00K/4846.18K
recv  [ ##------------------ ] 512.00K/4846.18K
recv  [ ###----------------- ] 768.00K/4846.18K
recv  [ ####---------------- ] 1024.00K/4846.18K
recv  [ #####--------------- ] 1280.00K/4846.18K
recv  [ ######-------------- ] 1536.00K/4846.18K
recv  [ #######------------- ] 1792.00K/4846.18K
recv  [ ########------------ ] 2048.00K/4846.18K
recv  [ #########----------- ] 2304.00K/4846.18K
recv  [ ##########---------- ] 2560.00K/4846.18K
recv  [ ###########--------- ] 2816.00K/4846.18K
recv  [ ############-------- ] 3072.00K/4846.18K
recv  [ #############------- ] 3328.00K/4846.18K
recv  [ ##############------ ] 3584.00K/4846.18K
recv  [ ###############----- ] 3840.00K/4846.18K
recv  [ ################---- ] 4096.00K/4846.18K
recv  [ #################--- ] 4352.00K/4846.18K
recv  [ ###################- ] 4608.00K/4846.18K
recv  [ #################### ] 4846.18K/4846.18K
Done! Using 0.10 s

在D:\recv\下找到传输的文件,发现文件损坏。
应该是发送时使用sendall发送出现的粘包或者缓存的问题。因此使用send版本,buffersize与接收方对应,并增加延时。
使用局域网的两台电脑实验通过。

你可能感兴趣的:(python socket)