python thread and communication with server(for My Wife test)

#!/usr/bin/env python

"""PyQt4 port of the dialogs/findfiles example from Qt v4.x"""
import sys,os
import time
from PySide import QtCore, QtGui
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtCore import Signal
import socket
import sys
import threading
from thread import *
 

from ui_main import Ui_Form

'''exitFlag = 0
def print_time(threadName, delay, counter):
	while counter:
		if exitFlag:
			threading.Thread.exit()
		time.sleep(delay)
		print "%s: %s" % (threadName, time.ctime(time.time()))
		counter -= 1

class myThread (threading.Thread):
	def __init__(self, threadID, name, counter):
		threading.Thread.__init__(self)
		self.threadID = threadID
		self.name = name
		self.counter = counter
	def run(self):
		print "Starting " + self.name
		print_time(self.name, self.counter, 5)
		print "Exiting " + self.name
'''
class RecvThread (threading.Thread):
	def __init__(self, threadID, name, client_name,function):
		#super(RecvThread, self).__init__(self)  
		threading.Thread.__init__(self)
		self.threadID = threadID
		self.name = name
		self.client_name = client_name
		self.func = function
		self.doRecv = True
	def run(self):
		print "recvThread run........"
		while self.doRecv:
			try:
				data = self.client_name.recv(2048)
				print data
				reply = 'OK, recv data: ' + data
				if not data: 
					break
				self.func(data)
			except socket.error , msg:
				print 'recv failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
				self.func("disconnect")
				self.doRecv = False
				self.client_name.close()
		
		

class ConnThread(QThread):
	def __init__(self, threadID, thread_name, client_name):
		QThread.__init__(self, parent=None)
		print "thread init.."
		self.threadID = threadID
		self.name = thread_name
		self.client_name = client_name
		self.conn = ''
		self.doConn = True
	def run(self):
		print "connThread run........"
		while self.doConn:
			self.conn, self.addr = self.client_name.accept()
			self.tp_string = 'Server connected with ' + self.addr[0] + ':' + str(self.addr[1]) + '\n'
			print self.tp_string
			#self.updateconnUI(self.tp_string)
			self.emit(SIGNAL("updatestring(QString)"),self.tp_string)
			print "show on screen."
			self.thread2 = RecvThread(2, "recvThread-2", self.conn, self.updateconnUI)
			self.thread2.start()
			print "create thread done"
			#self.connSignal.emit(self.tp_string)
		self.client_name.close()
	
	def sendMsg(self,str):
		self.conn.send(str)

 	def updateconnUI(self,str):
		print  "conn Thread update UI..1"
		print str
		if str == "disconnect":
			#self.thread2.stop()
			self.emit(SIGNAL("updatestring(QString)"),"server disconnect.\n")
		else:
			self.emit(SIGNAL("updateui(QString)"),str)

class AppMain(QtGui.QWidget):
	def __init__(self, parent=None):
		super(AppMain, self).__init__(parent)
		print "1"
		self.ui = Ui_Form()
		print "2"
		self.ui.setupUi(self)
		#thread1 = myThread(1, "Thread-1", 1)
		#thread2 = myThread(2, "Thread-2", 2)
		#thread1.start()
		#thread2.start()
		self.gsock_flag = False
		self.ui.pushButto_update.clicked.connect(self.updatefunc)
		#self.ipList = socket.gethostbyname_ex(socket.gethostname())
		self.ui.lineEdit_ip.setText(socket.gethostbyname(socket.gethostname()))
		self.ui.lineEdit_port.setText("8888")
		self.HOST = self.ui.lineEdit_ip.text() # Symbolic name meaning all available interfaces
		self.PORT = int(self.ui.lineEdit_port.text()) # Arbitrary non-privileged port
		#self.IP = socket.gethostbyname(socket.gethostname())
		print self.HOST
		print self.PORT
		self.ui.pushButto_send.clicked.connect(self.send_data_func)

		#self.appSlotFunctionInit()
		self.ui_str = ''
		self.tp_string = ''
		self.ui.textEdit_info.setPlainText("welcome~~~to connect: "+ socket.gethostbyname(socket.gethostname()) +"\n" + "port: 8888" + "\n")
		print "init Done"

	def updatefunc(self):
		self.HOST = self.ui.lineEdit_ip.text() # Symbolic name meaning all available interfaces
		self.PORT = int(self.ui.lineEdit_port.text()) # Arbitrary non-privileged port
		self.ui.textEdit_info.setPlainText("welcome~~~to connect: "+ self.HOST +"\n" + self.ui.lineEdit_port.text() + "\n")
		self.appSlotFunctionInit()

	def updateString(self, str):
		self.sstr = self.ui.textEdit_info.toPlainText() + str
		print self.sstr
		self.ui.textEdit_info.setPlainText(self.sstr)
		
	def updateMainUI(self, str):
		print "update UI MAIN"
		print str
		print "get str..."
		self.sstr = self.ui.textEdit_info.toPlainText() +'<recv:> ' + str
		print self.sstr
		#self.signal_handler(self.sstr)
		self.ui.textEdit_info.setPlainText(self.sstr)
		
	def dragEnterEvent(self, event):
		print "AppMain dragEnterEvent"
		event.accept()

	def dropEvent(self, event):
		print "AppMain dropEvent"

	def initThread(self, name, delay):
		while 1:
			#wait to accept a connection - blocking call
			self.conn, self.addr = self.s.accept()
			self.tp_string = 'Connected with ' + self.addr[0] + ':' + str(self.addr[1])
			print self.tp_string
			print "show on screen."
			#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
			#start_new_thread(self.clientthread,(self.conn,))
			#start_new_thread(Data(),(self.conn,))
		self.s.close()
		print "end thread."

	def appSlotFunctionInit(self):
		print "appSlotFunctionInit"
		if self.gsock_flag == False:
			print "1"
		else:
			print "2 close socket"
			self.s.close()
			time.sleep(1)
			self.gsock_flag = False


		#self.thread = Gclientthread()
		#self.connect(self.thread, QtCore.SIGNAL("updateui()"),self.updateUI)
		print "connect mySignal"
		try:
			print "appGloableDataInit"
			self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			print 'Socket created'
			 
			#Bind socket to local host and port
			try:
				print "bind"
				self.s.bind((self.HOST,self.PORT))
				print "bind success"
			except socket.error , msg:
				print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
				self.s.close()
				self.gsock_flag = False
				self.ui.textEdit_info.setPlainText("Bind failed....!!!!....\n")
				#sys.exit()
				 
			print 'Socket bind complete'
			 
			#Start listening on socket
			self.s.listen(10)
			print 'Socket now listening'
			self.gsock_flag = True

			self.thread = ConnThread(1,"conn_thread_1",self.s)
			self.connect(self.thread, QtCore.SIGNAL("updateui(QString)"), self.updateMainUI)
			self.connect(self.thread, QtCore.SIGNAL("updatestring(QString)"), self.updateString)
			self.thread.start()
			print "create connThread done"
		except:
			print "Error: !!!!!!unable to start thread"
		print "end slot"

	def send_data_func(self):
		str = self.ui.textEdit_send_msg.toPlainText()
		print str
		self.thread.sendMsg(str)
		input_str = self.ui.textEdit_info.toPlainText() + "<send:> " + str + '\n'
		self.ui.textEdit_info.setPlainText(input_str)

def main():
	app = QApplication(sys.argv)
	d = AppMain()
	d.show()
	app.exec_()

if __name__ == '__main__':
	try:
		main()
	except:
		print("Error: new MainWindow error.")
		pass

  

posted @ 2017-08-19 13:04  JustRelax  阅读(154)  评论(0编辑  收藏  举报