def on_delete_news(self): news = {} news["header"] = self.mainWnd.newsCurWnd.ui.leTitle.text() news["date"] = self.mainWnd.newsCurWnd.ui.lbTime.text().split(">")[5].split("<")[0] news["user"] = self.mainWnd.user self.newsTmr.stop() self.del_news.set_news(news) self.del_news.start() client = TcpClient() client.connect(self.mainWnd.TCPServer, self.mainWnd.TCPPort, self.mainWnd.user, self.mainWnd.passwd) client.delete_news(self.mainWnd.newsCurWnd.ui.leTitle.text()) client.close()
class Main(QWidget, Ui_Form): def __init__(self, parent=None): QWidget.__init__(self, parent) self.setupUi(self) self.tcp_client = TcpClient() """---------------PyQt BUTTON LISTENERS---------------------""" #connect button pressed @pyqtSignature("") def on_connect_btn_pressed(self): try: self.tcp_client.connect() print "Client connected!" except Exception, e: print "Connect to server Failed!", e
class RecieveThread(QtCore.QThread, TcpConfig): err = QtCore.pyqtSignal(str) downloadStart = QtCore.pyqtSignal(str) decryptStart = QtCore.pyqtSignal() decompressStart = QtCore.pyqtSignal() downloadComplete = QtCore.pyqtSignal() fileDownloaded = QtCore.pyqtSignal(str) fileCount = QtCore.pyqtSignal(int) update = False cur_path = str def __init__(self): super(RecieveThread, self).__init__() self.client = TcpClient() QtCore.QObject.connect(self.client, QtCore.SIGNAL("downloadStart(QString)"), self.on_download_start) QtCore.QObject.connect(self.client, QtCore.SIGNAL("decryptStart()"), self.on_decrypt_start) QtCore.QObject.connect(self.client, QtCore.SIGNAL("decompressStart()"), self.on_decompress_start) QtCore.QObject.connect(self.client, QtCore.SIGNAL("downloadComplete()"), self.on_download_complete) QtCore.QObject.connect(self.client, QtCore.SIGNAL("fileDownloaded(QString)"), self.on_file_downloaded) QtCore.QObject.connect(self.client, QtCore.SIGNAL("fileCount(int)"), self.on_file_count) def set_configs(self, tcpserver, tcpport, usr, pwd, update, path): self.TCPServer = tcpserver self.TCPPort = tcpport self.user = usr self.passwd = pwd self.update = update self.cur_path = path def on_file_downloaded(self, fname): self.fileDownloaded.emit(fname) def on_download_start(self, fname): self.downloadStart.emit(fname) def on_decrypt_start(self): self.decryptStart.emit() def on_decompress_start(self): self.decompressStart.emit() def on_download_complete(self): self.downloadComplete.emit() def on_file_count(self, cnt): self.fileCount.emit(cnt) def run(self): if self.client.connect(self.TCPServer, self.TCPPort, self.user, self.passwd): self.client.get_files(self.update, self.cur_path) self.client.close()
class RecieveMsgThread(QtCore.QThread, TcpConfig): msgRecieved = QtCore.pyqtSignal([str, str, str]) msgNone = QtCore.pyqtSignal() def __init__(self): super(RecieveMsgThread, self).__init__() self.client = TcpClient() def set_configs(self, tcpserver, tcpport, usr, pwd): self.TCPServer = tcpserver self.TCPPort = tcpport self.user = usr self.passwd = pwd def run(self): if self.client.connect(self.TCPServer, self.TCPPort, self.user, self.passwd): msg = self.client.get_messages() if msg == "[EMPTY-MSG]": self.client.close() self.msgNone.emit() else: self.msgRecieved.emit(msg["FromUser"], msg["Time"], msg["Data"]) self.client.close()
#线程类 class keyBordInput(threading.Thread): def __init__(self, sock): threading.Thread.__init__(self) self._sock = sock def run(self): print('input \'quit\' to exit!') while True: msg = input(str(self._sock.localAdr) + ':') if msg == 'quit' or self._sock._closed: break self._sock.send(msg) self._sock.close() ''' 普通的客户端程序 ''' if __name__ == "__main__": IP = '169.254.252.124' port = 6000 client = TcpClient() client.connect(IP, port) #建立线程,用于接收键盘输入 th = keyBordInput(client) th.start() client.receive() print('remote server closed connection! press any key to exit!') th.join() print('client is closed!')
class SendFilesThread(QtCore.QThread): connectionStart = QtCore.pyqtSignal() err = QtCore.pyqtSignal(str) compressStart = QtCore.pyqtSignal(str) cryptStart = QtCore.pyqtSignal(str) sendStart = QtCore.pyqtSignal(str) sendComplete = QtCore.pyqtSignal() sendFileComplete = QtCore.pyqtSignal() def __init__(self): super(SendFilesThread, self).__init__() self.cfg = Configs() self.app_path = AppPath().main() self.a_key = AES256_cert_read("".join((self.app_path, "transf.crt"))) def send(self, wnd, TCPServer, TCPPort, flist, toUsr): """ Set connection configs """ self._wnd = wnd self._server = TCPServer self._port = TCPPort self.fileList = flist self._toUsr = toUsr def run(self): toUser = str("") self.client = TcpClient() mdb = MariaDB() if not mdb.connect(self._wnd.MDBServer, self._wnd.MDBUser, self._wnd.MDBPasswd, self._wnd.MDBBase): self.err.emit('Ошибка соединения с Базой Данных!') return toUser = mdb.get_user_by_alias(self._toUsr) mdb.close() if not os.path.exists("".join((self._wnd.app_path, "sendfiles"))): os.makedirs("".join((self._wnd.app_path,"sendfiles"))) self.connectionStart.emit() if not self.client.connect(self._server, self._port, self._wnd.user, self._wnd.passwd): print("fail connection") self.err.emit("Ошибка соединения с сервером!") return exts = [] try: exts = self.cfg.unzip_formats() except: Log().local("Error reading unzip formats") c_exts = [] try: c_exts = self.cfg.uncrypt_formats() except: Log().local("Error reading uncrypted formats") print("start send") self.client.begin_send_files(toUser) for sfile in self.fileList: lsf = sfile.split("/") l = len(lsf) fname = lsf[l - 1] """ Checking extension """ isCompress = True isCrypt = True tmp_fname = fname.split(".") ext = tmp_fname[len(tmp_fname) - 1].lower() for ex in exts: if ex == ext: isCompress = False break for ex in c_exts: if ex == ext: isCrypt = False break """ Rename file """ while True: try: parts = fname.split("'") fname = "" l = len(parts) i = 0 for part in parts: i += 1 if i < l: fname = fname + part + "_" else: fname = fname + part break except: break self.compressStart.emit(fname) if isCompress: if not zlib_compress_file(sfile, "".join((self._wnd.app_path, "sendfiles/", fname, ".z"))): Log().local("Error compressing send file: " + fname) print("error compressing") self.client.close() self.err.emit("Ошибка при сжатии файла") return else: print("".join((fname, " compressed"))) else: print(fname + " not compressed") shutil.copy2(sfile, "sendfiles/" + fname + ".z") if isCrypt: self.cryptStart.emit(fname) if not AES256_encode_file("".join((self._wnd.app_path, "sendfiles/", fname, ".z")), "".join((self._wnd.app_path, "sendfiles/", fname, ".bin")), self.a_key): Log().local("Error encrypting send file: " + fname) print("error crypting") self.client.close() self.err.emit("Ошибка при шифровании сообщения") else: print("".join((fname, " crypted"))) else: print(fname + " not crypt") shutil.copy2("".join((self._wnd.app_path,"sendfiles/", fname, ".z")), "".join((self._wnd.app_path,"sendfiles/", fname, ".bin"))) self.sendStart.emit(fname) self.client.send_file("".join((self._wnd.app_path, "sendfiles/", fname))) self.sendFileComplete.emit() try: os.remove("".join((self._wnd.app_path, "sendfiles/", fname, ".z"))) os.remove("".join((self._wnd.app_path, "sendfiles/", fname, ".bin"))) except: Log().local("Error filename") self.err.emit("Ошибка в имени файла!") self.client.end_send_files() self.sendComplete.emit() print("send complete") self.client.close()
def send_msg(wnd, msg, all, lUsrPwd, usr): """ Send message to remote tcp server """ answ = str toUser = str if msg == "": QtGui.QMessageBox.warning(wnd, 'Complete', 'Введите сообщение!', QtGui.QMessageBox.Yes) return if (usr == "") and (not all): """ If message sending to single user and user not selected then fail """ QtGui.QMessageBox.warning(wnd, 'Complete', 'Выберите пользователя!', QtGui.QMessageBox.Yes) return mdb = MariaDB() if not mdb.connect(wnd.MDBServer, wnd.MDBUser, wnd.MDBPasswd, wnd.MDBBase): QtGui.QMessageBox.critical(wnd, 'Ошибка', 'Ошибка соединения с Базой Данных!', QtGui.QMessageBox.Yes) return if not all: toUser = mdb.get_user_by_alias(usr) mdb.close() client = TcpClient() if not client.connect(wnd.TCPServer, wnd.TCPPort, wnd.user, lUsrPwd): QtGui.QMessageBox.critical(wnd, "Ошибка", "Ошибка соединения с сервером!", QtGui.QMessageBox.Yes) return if not all: answ = client.send_message(toUser, msg) else: answ = client.send_message("$ALL_USERS$", msg) client.close() if answ == "[FAIL]": QtGui.QMessageBox.critical(wnd, 'Ошибка', 'Ошибка передачи сообщения!', QtGui.QMessageBox.Yes) client.close() return if answ == "[FAIL-LEN]": QtGui.QMessageBox.critical(wnd, 'Ошибка', 'Сообщение слишком длинное!', QtGui.QMessageBox.Yes) client.close() return if answ == "[FAIL-ACCESS]": QtGui.QMessageBox.critical(wnd, 'Ошибка', 'У Вас нет прав на отправку всем пользователям!', QtGui.QMessageBox.Yes) client.close() return if answ == "[SEND-MSG-OK]": mb = MessageBase() if not all: mb.save_message(usr, msg, False) QtGui.QMessageBox.information(wnd, 'Complete', 'Сообщение отправлено!', QtGui.QMessageBox.Yes) else: mb.save_message("Всем", msg, False) QtGui.QMessageBox.information(wnd, 'Complete', 'Сообщение отправлено всем пользователям!', QtGui.QMessageBox.Yes)