require 'Qt'

class Client < TQt::VBox

    def initialize( host, port )
		super()
		# GUI layout
		@infoText = TQt::TextView.new( self )
		hb = TQt::HBox.new( self )
		@inputText = TQt::LineEdit.new( hb )
		send = TQt::PushButton.new( tr("Send") , hb )
		close = TQt::PushButton.new( tr("Close connection") , self )
		quit = TQt::PushButton.new( tr("Quit") , self )
	
		connect( send, TQ_SIGNAL('clicked()'), TQ_SLOT('sendToServer()') )
		connect( close, TQ_SIGNAL('clicked()'), TQ_SLOT('closeConnection()') )
		connect( quit, TQ_SIGNAL('clicked()'), $qApp, TQ_SLOT('quit()') )
	
		# create the socket and connect various of its signals
		@socket = TQt::Socket.new( self )
		connect( @socket, TQ_SIGNAL('connected()'),
			TQ_SLOT('socketConnected()') )
		connect( @socket, TQ_SIGNAL('connectionClosed()'),
			TQ_SLOT('socketConnectionClosed()') )
		connect( @socket, TQ_SIGNAL('readyRead()'),
			TQ_SLOT('socketReadyRead()') )
		connect( @socket, TQ_SIGNAL('error(int)'),
			TQ_SLOT('socketError(int)') )
	
		# connect to the server
		@infoText.append( tr("Trying to connect to the server\n") )
		@socket.connectToHost( host, port )
    end
	
	slots	'closeConnection()', 'sendToServer()',
			'socketReadyRead()', 'socketConnected()',
			'socketConnectionClosed()', 'socketClosed()',
			'socketError(int)'

    def closeConnection()
		@socket.close()
		if @socket.state() == TQt::Socket::Closing
			# We have a delayed close.
			connect( @socket, TQ_SIGNAL('delayedCloseFinished()'),
				TQ_SLOT('socketClosed()') )
		else
			# The socket is closed.
			socketClosed()
		end
    end

    def sendToServer()
		# write to the server
		os = TQt::TextStream.new(@socket)
		os << @inputText.text() << "\n"
		@inputText.setText( "" )
		os.dispose()
    end

    def socketReadyRead()
		# read from the server
		while @socket.canReadLine() do
	    	@infoText.append( @socket.readLine() )
		end
    end

    def socketConnected()
		@infoText.append( tr("Connected to server\n") )
    end

    def socketConnectionClosed()
		@infoText.append( tr("Connection closed by the server\n") )
    end

    def socketClosed()
		@infoText.append( tr("Connection closed\n") )
    end

    def socketError( e )
		@infoText.append( tr("Error number %d occurred\n" % e) )
    end
end

app = TQt::Application.new( ARGV )
client = Client.new( ARGV.length < 1 ? "localhost" : ARGV[0], 4242 )
app.mainWidget = client
client.show
app.exec
