python sendfile_client.py
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python sendfile_client.py相关的知识,希望对你有一定的参考价值。
import socket, select, string, sys, os
def prompt() :
sys.stdout.write('\n<You> ')
sys.stdout.flush()
if __name__ == "__main__":
# define server's name and port
host = 'localhost'
port = 5000
RECV_BUFFER = 1024
# create client socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# connect to remote host
try :
s.connect((host, port))
except :
print ' > Unable to connect'
sys.exit()
command = '*'
buf = ''
print ' > Connected to remote server'
prompt()
while 1:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock in read_sockets:
#incoming message from server
if sock == s:
data = sock.recv(RECV_BUFFER)
if not data :
print '\nDisconnected from server'
sys.exit()
elif data == 'File not found' :
print '\n > File not found'
prompt()
elif data == 'Command not found' :
print '\n > Command not found'
prompt()
else :
# get message header
message_header = data.partition('\n\n\n')
# get file size from message header
file_size = message_header[0].partition('file_size: ')
size = int(file_size[2])+len(message_header[0])+len(message_header[1])
# receive data from server
buf = data
print ' > Download : ',
while len(buf) < size:
print '......',
data = sock.recv(RECV_BUFFER)
buf += data
print ''
# get file name from last command
protocol = command.partition(" ")
# check if file already exist (delete if exist)
if os.path.exists(protocol[2]):
os.remove(protocol[2])
# get data file without message header
data_file = buf.partition('\n\n\n')
# write buffer data to new file
with open(protocol[2], 'wb') as file:
file.write(data_file[2])
# display message header
print '\nMessage Header :'
print message_header[0]
print ""
#close file after write
file.close()
print " > Download finish :)"
prompt()
#user entered a message
else :
msg = raw_input()
command = msg
s.send(msg)
以上是关于python sendfile_client.py的主要内容,如果未能解决你的问题,请参考以下文章