0

我正在尝试通过线程从多个点读取源计算机(客户端)中的文件并将块发送到目标(服务器)。我已经完成了客​​户端程序,但在服务器端我有 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()
4

1 回答 1

0

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

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

看看这个: http ://docs.python.org/library/multiprocessing.html

就实际问题而言,为您完成程序的人完全降低了它的乐趣。另外,这只是家庭作业作弊的味道。

于 2012-06-09T05:33:41.120 回答