Script test_client_py
[hide private]
[frames] | no frames]

Source Code for Script script-test_client_py

 1  #!/usr/bin/python 
 2  # A Python client for HTTPSpeaker. 
 3  __id__ = "$Id$" 
 4  __author__ = "Jason White" 
 5  __version__ = "$Revision$" 
 6  __date__ = "$Date$" 
 7  __copyright__ = "Copyright 2011 Jason White" 
 8  __license__ = "LGPL" 
 9   
10  from httplib import HTTPConnection, HTTPResponse 
11   
12 -class HTTPSpeakerError(Exception):
13 "Holds the HTTP status code and reason phrase returned by the server in the event of an error."
14 - def __init__(self, status, reason):
15 self.status = status 16 self.reason = reason
17 - def __str__(self):
18 return "Status code " + str(self.status) + ": " + self.reason
19
20 -class HTTPSpeakerClient:
21 """Emacspeak HTTP speech client, for HTTPSpeaker instances."""
22 - def __init__(self, host="127.0.0.1", port=8000):
23 "Initialize client to connect to server at given host and port." 24 self._connection=HTTPConnection(host, port)
25
26 - def postCommand(self, command, arg=""):
27 """Post command, with argument arg (default, empty), to the speech server. 28 Returns the body of the server's HTTP response, if any. On error, HTTPSpeakerError is raised.""" 29 body = command 30 if arg: 31 body += ": " + arg 32 self._connection.request("POST", "/", body, {"Content-type": "text/plain"}) 33 response=self._connection.getresponse() 34 if response.status != 200: 35 raise HTTPSpeakerError(response.status, response.reason) 36 return response.read()
37
38 - def speak(self, text):
39 "Speak the supplied string." 40 self.postCommand("speak", text)
41
42 - def stop(self):
43 "Stop speaking." 44 self.postCommand("stop")
45
46 - def isSpeaking(self):
47 "Return '0' when not speaking." 48 return self.postCommand("isSpeaking")
49
50 - def close(self):
51 "Close the connection to the speech server." 52 self._connection.close()
53 54 # Test the server (assumes localhost:8000). 55 if __name__ == '__main__': 56 client = HTTPSpeakerClient() 57 client.speak("Hello, world!") 58 print client.isSpeaking() 59 client.close() 60