Exemplo n.º 1
0
class ChatClient(QtCore.QObject):

	userName = ""
	
	# Constructor                                                                                                                             
	#
	def __init__(self, serverPort):
		self.app = QtGui.QApplication(sys.argv)
		super(ChatClient, self).__init__()
		self.serverPort = serverPort
		self.GUI = ChatGUI()
		self.GUI.connectMessageInput(self.send_message)
		self.clientThread = thread.start_new_thread(self.run, ())
		# Connects relevant signals to GUI slots
		self.connect(self, QtCore.SIGNAL("updateUsers"), self.GUI.setUserList)
		self.connect(self, QtCore.SIGNAL("addMessage"), self.GUI.addMessage)
		self.connect(self, QtCore.SIGNAL("exit"), self.GUI.exit)
		self.app.exec_()

	# process_command - Takes expected command line arguments to initialize username.
	#
	def process_command(self,command):
		if not command:
			print "Error, username not provided. Program terminated"
			sys.exit()
		else:
			self.userName = command

	# send_message - Obtains the text from chat input and sends them to server. 
	#				 PUT is prepended to indicate the method.
	#
	def send_message(self):
		message = self.GUI.chatInput.text().toAscii()
		if message:
			message = "PUT " + message
			self.GUI.chatInput.clear()
			self.serverSocket.send(message)
		self.GUI.chatInput.setFocus()		

	# get_data - Polls the server for the most recent users list and the most
	#			 recent chat log. The specific functionality of each is delegated
	#			 to an appropriate function call.
	#
	def get_data(self):
		while(1):
			time.sleep(.25)
			self.get_users()
			self.get_msgs()

	# get_users - Polls the server for the most recent list of users. This
	#			  list is sent to the GUI.
	#
	def get_users(self):
		message = "GETUSERS"
		try:
			self.serverSocket.send(message)
			chats = self.serverSocket.recv(4196)
			chatsArray = chats.split(" ",1)
			if chatsArray[0] == "USERS":
				self.emit(QtCore.SIGNAL("updateUsers"), chatsArray[1])
		except Exception, e:
			print "Error connecting to server"
			self.emit(QtCore.SIGNAL("exit"),)
			sys.exit(0)