def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.layout = QVBoxLayout() self.setLayout(self.layout) self.address = QLineEdit() self.address.setInputMask("\A\d\dress: 000.000.000.000") self.address.setText('192.168.001.069') self.port = QLineEdit() self.port.setInputMask("Port: 9000") self.port.setText('9110') self.btnConnect = QPushButton() self.btnConnect.clicked.connect(self.btnConnectClicked) self.statusBar = QStatusBar() self.layout.addWidget(self.address) self.layout.addWidget(self.port) self.layout.addWidget(self.btnConnect) self.layout.addWidget(self.statusBar) self.tcpClient = TcpClient() self.setWindowTitle('CAN Printer Logger v.{}'.format(self.version)) self.setWindowIcon(QIcon('icons/icon.png')) self.tcpClient.connectionFailed.connect(self.connectionFailed) self.tcpClient.tcpClientError.connect(self.connectionFailed) self.tcpClient.connected.connect(self.connected) self.tcpClient.disconnected.connect(self.disconnected) self.changeState(self.stDisconnected)
def __init__(self, marshaller, host, port): TcpClient.__init__(self, host, port) self.marshaller = marshaller self.order_books = {} self.referential = None self.handle_callbacks = { MessageTypes.Referential.value: self.handle_referential, MessageTypes.OrderBook.value: self.handle_order_book }
def __init__(self, user_name, debug=False): self.logger = add_log('mala_%s' % user_name, debug) self.user_id = 0 self.user_name = user_name self.tcp_client = TcpClient(self) self.tcp_client.setDaemon(True) self.tcp_client.start() self.user_data = None self.action_state = 0 self.enabled_actions = ['build', 'army', 'fast_forward']
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 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
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 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 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()
def __init__(self, login, password, marshaller, host, port): TcpClient.__init__(self, host, port) self.login = login self.password = password self.marshaller = marshaller self.handle_callbacks = {}
def __init__(self): super(RecieveMsgThread, self).__init__() self.client = TcpClient()
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 run(self): if self.task == "news": con = sqlite3.connect(self.cur_path + 'news.db') cur = con.cursor() try: cur.execute( 'CREATE TABLE news(id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR(512), date VARCHAR(20))') con.commit() except: pass mdb = MariaDB() if not mdb.connect(self.configs["MDBServer"], self.configs["MDBUser"], self.configs["MDBPasswd"], self.configs["MDBBase"]): self.err.emit("Ошибка соединения с Базой Данной", self.task) return news_list = mdb.check_news() l = len(news_list) if l != self.news_count: self.setNewsCount.emit(l) self.clearNews.emit() for news in news_list: cur.execute( "SELECT * FROM news WHERE title='" + news["title"] + "' and date='" + news["date"] + "'") n_list = cur.fetchall() if len(n_list) == 0: cur.execute( "INSERT INTO news(title, date) VALUES('" + news["title"] + "', '" + news["date"] + "')") con.commit() """ Show tooltip """ if not mdb.is_admin(self.user): self.showNewsBaloon.emit(news["date"], news["title"]) self.addInNews.emit(news["date"], news["title"]) mdb.close() con.close() self.checkNewsComplete.emit() self.exit(0) elif self.task == "msg_and_files": """ Checking server status (online/offline) """ client = TcpClient() if not client.check_status(self.configs["TcpServer"], self.configs["TcpPort"]): self.serverOffline.emit() else: self.serverOnline.emit() client.close() """ Checking update, messages, files """ mdb = MariaDB() if not mdb.connect(self.configs["MDBServer"], self.configs["MDBUser"], self.configs["MDBPasswd"], self.configs["MDBBase"]): self.err.emit("Ошибка соединения с Базой Данных!", self.task) return if mdb.check_update(self.user): mdb.close() print("Доступны обновления.") self.updateAvailable.emit() return if mdb.check_files(self.user): mdb.close() print("Есть новые файлы.") self.filesAvailable.emit() return if mdb.check_messages(self.user) and (not self.msg_status): mdb.close() print("Есть новые сообщения.") self.msgAvailable.emit() return mdb.close() self.nothingAvailable.emit() return
class UserClient(object): def __init__(self, user_name, debug=False): self.logger = add_log('mala_%s' % user_name, debug) self.user_id = 0 self.user_name = user_name self.tcp_client = TcpClient(self) self.tcp_client.setDaemon(True) self.tcp_client.start() self.user_data = None self.action_state = 0 self.enabled_actions = ['build', 'army', 'fast_forward'] def on_message(self, message): self.logger.debug('on_message#############################') self.logger.debug(message) self.logger.debug('#######################################') if message.result == 0: func = rsp.cmd_prot_rsp_method.get(message.cmd) if func is None: rsp.default_func(self, message) return self.logger.debug('func_name: ' + func.__name__) func(self, message) else: self.logger.debug(message) def send_message(self, cmd, data): self.logger.debug('send_message: ' + cmd) self.logger.debug(data) cs_info = sp.CsInfo(**data) cs_info.cmd = getattr(sp, cmd) cs_info.id = self.user_id send_af = AppFrame() send_af.message = cs_info send_af.frame_command = cs_info.cmd send_af.frame_id = cs_info.id self.tcp_client.send(send_af) def get_action_list(self): """agent使用 获取当前可用的Action""" self.update() self.full_resource() action_list = self._get_action_list() if not [a for a in action_list if a.status == 0]: if ActionLogin(self).run(): action_list = self._get_action_list() return action_list def _get_action_list(self): action_list = [] if 'build' in self.enabled_actions: action_list += create_build_actions(self) if 'army' in self.enabled_actions: action_list += create_army_actions(self) if 'fast_forward' in self.enabled_actions: action_list += create_fast_forward_actions(self) return action_list def get_user_data(self): """agent使用 获取游戏状态信息""" return copy.deepcopy(self.user_data) def update(self): self._update_progress() def _update_progress(self): pass def login(self): self.tcp_client.open() if ActionLogin(self).run(): return True self.tcp_client.close() return False def register(self): if self.login(): ActionMove(self).run() return True return False def heart(self): def _heart(): self.send_message('ReqHeart', {'req_heart': {'revert': 1}}) t = threading.Timer(30, _heart) t.setDaemon(True) t.start() timer = threading.Timer(30, _heart) timer.setDaemon(True) timer.start() def add_cash(self, cash=1000): data = { 'req_gm': { 'gm_info': { 'gm_cmd': ['add_cash', str(cash)] } } } self.send_message('ReqGM', data) def add_resource(self, _type, num): num = str(num) if _type == 'cash': gm_cmd = ['add_cash', num] elif _type == 'energy': gm_cmd = ['add_resource', '0', num] elif _type == 'mineral': gm_cmd = ['add_resource', '1', num] elif _type == 'crystal': gm_cmd = ['add_resource', '2', num] elif _type == 'alloy': gm_cmd = ['add_resource', '3', num] else: return data = { 'req_gm': { 'gm_info': { 'gm_cmd': gm_cmd } } } self.send_message('ReqGM', data) def full_resource(self): energy_max = self.user_data['city_count']['energy_max'] mineral_max = self.user_data['city_count']['mineral_max'] energy = energy_max - self.user_data['base_info']['energy'] mineral = mineral_max - self.user_data['base_info']['mineral'] if energy > 0: self.add_resource('energy', energy) self.user_data['base_info']['energy'] = energy_max if mineral > 0: self.add_resource('mineral', mineral) self.user_data['base_info']['mineral'] = mineral_max self.logger.debug('add_resource: %s%s' % (energy, mineral)) if self.user_data['base_info']['crystal'] < 100: self.add_resource('crystal', 1000) self.user_data['base_info']['crystal'] += 1000 if self.user_data['base_info']['alloy'] < 100: self.add_resource('alloy', 1000) self.user_data['base_info']['alloy'] += 1000
class MainWindow(QWidget): version = '1.1' stDisconnected = 0 stConnected = 1 def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.layout = QVBoxLayout() self.setLayout(self.layout) self.address = QLineEdit() self.address.setInputMask("\A\d\dress: 000.000.000.000") self.address.setText('192.168.001.069') self.port = QLineEdit() self.port.setInputMask("Port: 9000") self.port.setText('9110') self.btnConnect = QPushButton() self.btnConnect.clicked.connect(self.btnConnectClicked) self.statusBar = QStatusBar() self.layout.addWidget(self.address) self.layout.addWidget(self.port) self.layout.addWidget(self.btnConnect) self.layout.addWidget(self.statusBar) self.tcpClient = TcpClient() self.setWindowTitle('CAN Printer Logger v.{}'.format(self.version)) self.setWindowIcon(QIcon('icons/icon.png')) self.tcpClient.connectionFailed.connect(self.connectionFailed) self.tcpClient.tcpClientError.connect(self.connectionFailed) self.tcpClient.connected.connect(self.connected) self.tcpClient.disconnected.connect(self.disconnected) self.changeState(self.stDisconnected) def closeEvent(self, event): self.disconnectFromPrinter() event.accept() def btnConnectClicked(self): if self._state == self.stConnected: self.disconnectFromPrinter() self.statusBar.showMessage("Disconnecting...") log.debug('Start disconnecting') else: self.statusBar.showMessage("Connecting...") self.connectToPrinter() def disconnectFromPrinter(self): self.tcpClient.disconnectFromHost(0) def connectionFailed(self, text): self.statusBar.showMessage(text) def connectToPrinter(self): if self.address.hasAcceptableInput(): ip = self.address.text() ip = self.address.text().strip('Address: ') else: QMessageBox.warning('Error', 'Incorrect ip-addres!') ip = None if self.port.hasAcceptableInput(): port = int(self.port.text().strip('Port: ')) else: QMessageBox.warning('Error', 'Incorrect port!') port = None if ip is not None and port is not None: self.tcpClient.connectToHost(ip, port) log.debug("Connect to {}:{}".format(ip, port)) def changeState(self, state): if state == self.stConnected: self.btnConnect.setIcon(QIcon("icons/disconnect.png")) self.btnConnect.setText('Disconnect') self.btnConnect.setToolTip('Stop logging') self.statusBar.showMessage("Logging...") self._state = self.stConnected else: self.btnConnect.setIcon(QIcon("icons/connect.png")) self.btnConnect.setText('Сonnect') self.btnConnect.setToolTip('Start logging') self.statusBar.showMessage("Disconnected", 5000) self._state = self.stDisconnected def disconnected(self): self.changeState(self.stDisconnected) def connected(self): self.changeState(self.stConnected)
while True: msg = input(str(self._sock.localAdr) + ':') if msg == 'quit' or self._sock._closed: break print("send...") self._sock.crytoSend(msg) self._sock.close() ''' 加密的客户端程序 ''' if __name__ == "__main__": IP = '169.254.252.124' port = 6001 client = TcpClient() client.connect(IP, port) #等待接收对方公钥 cryto = CryptoModule() client.setCryto(cryto) publicKey = client.receiveKey() print(publicKey.decode()) cryto.importPublicKey(publicKey) cryto.GenerateAseKey() print('-------------AseKey------------') # print(len(cryto.exportAseKey())) aseKey = cryto.RsaEncryptCipher.encrypt(cryto.exportAseKey()) client.sendKey(aseKey) # print(len(aseKey)) #建立线程,用于接收键盘输入 th = keyBordInput(client)
def __init__(self, parent=None): QWidget.__init__(self, parent) self.setupUi(self) self.tcp_client = TcpClient()
#线程类 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!')
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)