summaryrefslogtreecommitdiff
path: root/py/demo/Ice/session/Client.py
blob: 68572b02cd5f5addd4a3d8cb6efad2d46350f65a (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# **********************************************************************

import sys, threading, Ice

Ice.loadSlice('Session.ice')
import Demo

class SessionRefreshThread(threading.Thread):
    def __init__(self, logger, timeout, session):
        threading.Thread.__init__(self)
        self._logger = logger
        self._session = session
        self._timeout = timeout
        self._terminated = False
        self._cond = threading.Condition()

    def run(self):
        self._cond.acquire()
        try:
            while not self._terminated:
                self._cond.wait(self._timeout)
                if not self._terminated:
                    try:
                        self._session.refresh()
                    except Ice.LocalException as ex:
                        self._logger.warning("SessionRefreshThread: " + str(ex))
                        self._terminated = True
        finally:
            self._cond.release()

    def terminate(self):
        self._cond.acquire()
        try:
            self._terminated = True
            self._cond.notify()
        finally:
            self._cond.release()

class Client(Ice.Application):
    def run(self, args):
        if len(args) > 1:
            print(self.appName() + ": too many arguments")
            return 1

        while True:
            sys.stdout.write("Please enter your name ==> ")
            sys.stdout.flush()
            name = sys.stdin.readline().strip()
            if len(name) != 0:
                break

        base = self.communicator().propertyToProxy('SessionFactory.Proxy')
        factory = Demo.SessionFactoryPrx.checkedCast(base)
        if not factory:
            print(args[0] + ": invalid proxy")
            return 1

        session = factory.create(name)
        try:
            refresh = SessionRefreshThread(self.communicator().getLogger(), 5, session)
            refresh.start()

            hellos = []

            self.menu()

            destroy = True
            shutdown = False
            while True:
                try:
                    sys.stdout.write("==> ")
                    sys.stdout.flush()
                    c = sys.stdin.readline().strip()
                    s = str(c)
                    if s.isdigit():
                        index = int(s)
                        if index < len(hellos):
                            hello = hellos[index]
                            hello.sayHello()
                        else:
                            print("Index is too high. " + str(len(hellos)) + " hello objects exist so far.\n" +\
                                  "Use `c' to create a new hello object.")
                    elif c == 'c':
                        hellos.append(session.createHello())
                        print("Created hello object",len(hellos) - 1)
                    elif c == 's':
                        destroy = False
                        shutdown = True
                        break
                    elif c == 'x':
                        break
                    elif c == 't':
                        destroy = False
                        break
                    elif c == '?':
                        self.menu()
                    else:
                        print("unknown command `" + c + "'")
                        self.menu()
                except EOFError:
                    break
                except KeyboardInterrupt:
                    break
            #
            # The refresher thread must be terminated before destroy is
            # called, otherwise it might get ObjectNotExistException. refresh
            # is set to 0 so that if session->destroy() raises an exception
            # the thread will not be re-terminated and re-joined.
            #
            refresh.terminate()
            refresh.join()
            refresh = None

            if destroy:
                session.destroy()
            if shutdown:
                factory.shutdown()
        finally:
            #
            # The refresher thread must be terminated in the event of a
            # failure.
            #
            if refresh != None:
                refresh.terminate()
                refresh.join()

        return 0

    def menu(self):
        print("""
usage:
c:     create a new per-client hello object
0-9:   send a greeting to a hello object
s:     shutdown the server and exit
x:     exit
t:     exit without destroying the session
?:     help
""")

app = Client()
sys.exit(app.main(sys.argv, "config.client"))