summaryrefslogtreecommitdiffstats
path: root/qtruby/rubylib/examples/network/clientserver/client/client.rb
blob: 85e769cb1861a0805f83dff33193c8ab5719ebec (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
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