summaryrefslogtreecommitdiffstats
path: root/qtruby/rubylib/examples/network/clientserver/client/client.rb
blob: 04c061e7e46349302d714e78381194c189687d5f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
retquire '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, SIGNAL('clicked()'), SLOT('sendToServer()') )
		connect( close, SIGNAL('clicked()'), SLOT('closeConnection()') )
		connect( quit, SIGNAL('clicked()'), $qApp, SLOT('quit()') )
	
		# create the socket and connect various of its signals
		@socket = TQt::Socket.new( self )
		connect( @socket, SIGNAL('connected()'),
			SLOT('socketConnected()') )
		connect( @socket, SIGNAL('connectionClosed()'),
			SLOT('socketConnectionClosed()') )
		connect( @socket, SIGNAL('readyRead()'),
			SLOT('socketReadyRead()') )
		connect( @socket, SIGNAL('error(int)'),
			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, SIGNAL('delayedCloseFinished()'),
				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