关于python的套接字备份

时间:2011-12-03 04:04:17

标签: python sockets

我编写了一个python脚本来备份我的文件,比如Dropbox。

但是有一些错误。我有一个名为SyncServer的课程,分别有两个名为__init__TF1的函数。 TF1代表“线程函数1”。

当我写第一个参数thread.start_new_thread(TF1, (conn, 0))时,我发送了一个套接字对象。不幸的是,python的IDLE回复了一个错误:NameError: global name 'TF1' is not defined

# -*- coding: cp950 -*-
import wx, socket, os, md5, thread, threading
class SyncClient:HOST = "127.0.0.1"
def __init__(self):
    self.config = {}
    open("sync.config", "a").close()
    f = open("sync.config", "r")
    line = f.readline()
    while line:
        tmp = line.split(":")
        self.config[tmp[0]] = ":".join(tmp[1:]).split("\n")[0]
        line = f.readline()
    f.close()
    ex = wx.App()
    ex.MainLoop()
    if (not self.config.has_key("id")) or (not self.config.has_key("password")) or (not self.config.has_key("port")) or (not self.config.has_key("path")):
        wx.MessageBox('something wrong. Q__________________________Q', 'Error', 
        wx.OK | wx.ICON_ERROR)
        return
    if (not os.access(self.config["path"], os.F_OK)):
        wx.MessageBox("It seems that " + self.config["path"] + " doesn't exist.", 'Error', 
        wx.OK | wx.ICON_ERROR)
        return
    if int(self.config['port']) > 5:
        wx.MessageBox('something wrong. Q__________________________Q', 'Error', 
        wx.OK | wx.ICON_ERROR)
        return
    chpswd = md5.new(self.config['password']).hexdigest()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((self.HOST, 7575))
    self.s = s;
    s.send("CHECK ID")
    if s.recv(1024) != "200 OK":
        return
    s.send(config['id'] + ";;" + chpswd)
    if s.recv(1024) == "False":
        wx.MessageBox("id and password not match.", 'Error', 
        wx.OK | wx.ICON_ERROR)
        return
    self.path = []

    for root, dirs, files in os.walk(self.config['path']):
        for f in files:
            self.path.append(root + f)
            self.s.send("FILE NAME")
            if self.s.recv(1024) != "200 OK":
                continue
            self.s.send(f)
            if self.s.recv(1024) != "200 OK":
                continue
            self.s.send("FILE LEN")
            if self.s.recv(1024) != "200 OK":
                continue
            cut = file_cut(root + f)
            self.s.send(len(cut))
            MakeThread(cut)
def MakeSocket(self):
    self.s.send("GIVE ME A PORT")
    port = int(self.s.recv(1024))
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((self.HOST, port))
    return s
def MakeThread(self, cut):
    self.ptr = 0
    s = MakeSocket()
    for i in self.config['port']:
        #s = MakeSocket()
        thread.start_new_thread(TF, (s, cut))
def TF(self, Socket, cut):
    l = len(cut)
    while self.ptr < l:
        Socket.send(self.ptr)
        if Socket.recv(1024) != "200 OK":
            continue
        Socket.send(cut[self.ptr])
        self.ptr += 1
    Socket.close()
def file_cut(self, path):
    f = open(path, "rb")
    content = f.read()
    cut = []
    l = len(content)
    i = 0
    while i < l:
        cut.append(content[i:i+1024])
        i += 1024
    return cut
'''f = open(path, "rb")
cont = f.read()
f.close()
fsize = len(cont)
fname = path.split("\\")[-1]
self.com.send(fname)
check = self.com.recv(1024)
if check != "200 OK": return 
self.com.send(str(fsize))
check = self.com.recv(1024)
if check != "200 OK": return 
i = 0
while i < fsize + 1025:
    Socket.send(cont[i:i+1024])
    i += 1024'''
def file_recv(self, Socket, path=".\\"):
    fname = self.com.recv(1024)
    self.com.send("200 OK")
    f = open(path + fname, "wb")
    fsize = self.com.recv(1024)
    self.com.send("200 OK")
    i = 0
    while i < fsize + 1025:
        line = Socket.recv(1024)
        f.write(line)
        f.flush()
        i += 1024
    f.close()
class SyncServer:
    def TF1(self, Socket, null):
        while True:
            data = Socket.recv(1024)
            if data == "CHECK ID":
                Socket.send("200 OK!")
                user = Socket.recv(1024)
                u = open("uid.txt","r")
                while True:
                    udata = u.readline().split(" ")
                    if udata == "":
                        Socket.send("False")
                        break
                    if user.split(";;")[0] == udata[0]:
                        Flag = True
                        if user.split(";;")[1] != md5.hexidigest(udata[1]):
                            Socket.send("False")
                        else:
                            self.user = user.split(";;")[0]
                            self.files[self.user] = []
                            Socket.send("True")
                        break
            if data == "GIVE ME A PORT":
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.bind(("", self.portList[0]))
                s.listen(1)
                Socket.send(self.portList[0])
                for i in range(0, flen):
                    thread.start_new_thread(TF2, (s.accept(), 0))
                f = open(fname, "wb")
                for line in self.files[self.user]:
                    f.write(line)
                f.close()
                #self.port
            if data == "FILE NAME":
                Socket.send("200 OK")
                fname = Socket.recv(1024)
                Socket.send("200 OK")
            if data == "FILE LEN":
                Socket.send("200 OK")
                flen = int(Socket.recv(1024))
    def TF2(self, Socket, null):
        idx = Socket.recv(1024)
        Socket.send("200 OK")
        line = Socket.recv(1024)
        self.files[self.user][idx] = line
    def __init__(self):
        self.portList = []
        self.files = {}
        for i in range(7576,7700):
            self.portList.append(i)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(("", 7575))
        s.listen(1)
        while True:
            conn, addr = s.accept()
            thread.start_new_thread(TF1, (conn, 0))

1 个答案:

答案 0 :(得分:4)

thread.start_new_thread(TF1, (conn, 0))

假设TF1是全球性的。

"NameError: global name 'TF1' is not defined"

说明TF1 是全球性的。

一定是假设是错误的。

TF1是类中的方法函数。因此,它需要通过类名或对象实例进行限定。通常,self.TF1是合适的。

请查找涵盖类定义的Python教程。