带套接字的python多线程文件传输

时间:2012-06-09 05:25:20

标签: multithreading client-server python-2.7 data-transfer serversocket

我正在尝试通过线程从多个点读取源计算机(客户端)中的文件,并将块发送到目标(服务器)。我已经完成了客​​户端程序,但是在服务器端我有3个问题:1 - 我无法通过多线程同时将块连接到文件.2 - 我不能将缓冲区的大小增加到8KB以上.3我有在一些尝试中发送不成功。我可以请你帮忙完成我的代码吗? 这是我的客户代码:

import socket
import Queue
import threading
import filechunkio,os.path
class VRCThread(threading.Thread):
    """Mostafa.Hadi"""
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue
    def Upload(self):
        file = self.queue.get()
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect(('172.32.60.45', 9999))
            chunk =filechunkio.FileChunkIO('piano.zip', offset=int(file)*8024, bytes=8024)
            k1=chunk.read()
            k1=k1[0:8024]+"piano.zip."+file
            sock.sendall(k1)
            sock.close()
        except Exception:
           print file+" UnSuccessful upload."
        else:
           print file+" Successful upload."
    def run(self):
        while True:
            self.Upload()
def main():
    queue = Queue.Queue()
    print "Connected to server"
    for i in range(8):
        t = VRCThread(queue)
        t.setDaemon(True)
        t.start()
    siz=os.path.getsize("piano.zip")
    num=siz/8024
    print num
    print siz
    for file in range(num):
        queue.put(str(file))
        print file
    queue.join()
if __name__=="__main__":
        main()

服务器端代码:

import SocketServer
import threading
import Queue

class MyServerThread(threading.Thread):

    def __init__(self, channel, details):
        self.channel = channel
        self.details = details
        threading.Thread.__init__(self)

    def run(self):
        print 'Received connection:', self.details[0]
        self.k= self.channel.recv(8040)
        self.channel.close()
        namef=self.k[8024:]
        v=open(namef,"wb")
        v.write(self.k)
        v.close

        print 'Closed connection:', self.details[0]

class MyThreadedSocketServerHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        thread1 = MyServerThread(self.request, self.client_address)
        thread1.start()
        thread1.join()
if __name__ == '__main__':
    server = SocketServer.TCPServer(('172.32.60.45', 9999), MyThreadedSocketServerHandler)
    server.serve_forever()

1 个答案:

答案 0 :(得分:0)

Python中的线程是一种痛苦。由于全局解释器锁定,一次只能运行一个线程。

http://docs.python.org/glossary.html#term-global-interpreter-lock

检查一下: http://docs.python.org/library/multiprocessing.html

就实际问题而言,为您完成计划的人会完全放弃它的乐趣。另外,这只是家庭作业作弊的气味。