Linux教程網
Python socket上傳文件的服務端和客戶端實現
代碼均已測試:希望高人能指點一二
服務端:
- #coding=gbk
- '''''
- 等待連接
- 等待發送文件
- 讀取數據
- 寫入文件並且保存
- 等待連接
- '''
- import socket
- import threading
- import time
- import struct
- def function(newsock, address):
- FILEINFO_SIZE = struct.calcsize('128sI')
- '''''定義文件信息(包含文件名和文件大小)大小。128s代表128個char[](文件名),I代表一個integer or long(文件大小)'''
- while 1:
- try:
- fhead = newsock.recv(FILEINFO_SIZE)
- filename, filesize = struct.unpack('128sI', fhead)
- '''''把接收到的數據庫進行解包,按照打包規則128sI'''
- print "address is: ",address
- print filename, len(filename),type(filename)
- print filesize
- filename = 'new_'+filename.strip('\00')#命名新文件new_傳送的文件
- fp = open(filename,'wb')#新建文件,並且准備寫入
- restsize = filesize
- print "recving..."
- while 1:
- if restsize > 1024:#如果剩余數據包大於1024,就去1024的數據包
- filedata = newsock.recv(1024)
- else:
- filedata = newsock.recv(restsize)
- fp.write(filedata)
- break
- if not filedata:
- break
- fp.write(filedata)
- restsize = testsize - len(filedata)#計算剩余數據包大小
- if restsize <= 0:
- break
- fp.close()
- print "recv succeeded !!File named:",filename
- except:
- print "he socket partner maybe closed"
- newsock.close()
- break
- sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)#創建tcp連接
- sock.bind(('127.0.0.1',8887))#定於端口和ip
- sock.listen(5)#監聽
- while True:
- newsock, address = sock.accept()
- print "accept another connection"
- tmpThread = threading.Thread(target=function,args=(newsock,address)) #如果接收到文件,創建線程
- tmpThread.start()#執行線程
- print 'end'
客戶端:
- #coding=gbk
- '''''
- 輸入文件名,並且上傳
- '''
- import socket
- import time
- import struct
- import os
- sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
- sock.settimeout(1)
- e=0
- try:
- sock.connect(('127.0.0.1',8887))
- print 'connect...'
- except socket.timeout,e:
- print 'timeout',e
- except socket.error,e:
- print 'error',e
- except e:
- print 'any',e
- if not e:
- while (1):
- filename = raw_input('input your filename------->')#輸入文件名
- FILEINFO_SIZE = struct.calcsize('128sI')#編碼格式大小
- fhead = struct.pack('128sI',filename,os.stat(filename).st_size)#按照規則進行打包
- sock.send(fhead)#發送文件基本信息數據
- fp = open(filename,'rb')
- while 1: #發送文件
- filedata = fp.read(1024)
- if not filedata:
- break
- sock.send(filedata)
- print "sending over..."
- fp.close()
Copyright ©
Linux教程網 All Rights Reserved