connection-ref.txt 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. .. include:: header.txt
  2. =======================
  3. Listeners and Clients
  4. =======================
  5. Usually message passing between processes is done using queues or by
  6. using connection objects returned by `Pipe()`.
  7. However, the `processing.connection` module allows some extra
  8. flexibility. It basically gives a high level API for dealing with
  9. sockets or Windows named pipes, and also has support for *digest
  10. authentication* using the `hmac` module from the standard library.
  11. Classes and functions
  12. =====================
  13. The module defines the following functions:
  14. `Listener(address=None, family=None, backlog=1, authenticate=False, authkey=None)`
  15. Returns a wrapper for a bound socket or Windows named pipe
  16. which is 'listening' for connections.
  17. `Client(address, family=None, authenticate=False, authkey=None)`
  18. Attempts to set up a connection to the listener which is using
  19. address `address`, returning a `connection object
  20. <connection-object.html>`_.
  21. The type of the connection is determined by `family`
  22. argument, but this can generally be omitted since it can
  23. usually be inferred from the format of `address`.
  24. If `authentication` or `authkey` is a string then digest
  25. authentication is used. The key used for authentication will
  26. be either `authkey` or `currentProcess.getAuthKey()` if
  27. `authkey` is `None`. If authentication fails then
  28. `AuthenticationError` is raised. See `Authentication keys`_.
  29. ..
  30. `deliverChallenge(connection, authkey)`
  31. Sends a randomly generated message to the other end of the
  32. connection and waits for a reply.
  33. If the reply matches the digest of the message using `authkey`
  34. as the key then a welcome message is sent to the other end of
  35. the connection. Otherwise `AuthenticationError` is raised.
  36. `answerChallenge(connection, authkey)`
  37. Receives a message, calculates the digest of the message using
  38. `authkey` as the key, and then sends the digest back.
  39. If a welcome message is not received then
  40. `AuthenticationError` is raised.
  41. The module exports two exception types:
  42. **exception** `AuthenticationError`
  43. Exception raised when there is an authentication error.
  44. **exception** `BufferTooShort`
  45. Exception raise by the `recvBytesInto()` method of a
  46. connection object when the supplied buffer object is too small
  47. for the message read.
  48. If `e` is an instance of `BufferTooShort` then `e.args[0]` will
  49. give the message as a byte string.
  50. Listener objects
  51. ================
  52. Instances of `Listener` have the following methods:
  53. `__init__(address=None, family=None, backlog=1, authenticate=False, authkey=None)`
  54. `address`
  55. The address to be used by the bound socket
  56. or named pipe of the listener object.
  57. `family`
  58. The type of the socket (or named pipe) to use.
  59. This can be one of the strings `'AF_INET'` (for a TCP
  60. socket), `'AF_UNIX'` (for a Unix domain socket) or
  61. `'AF_PIPE'` (for a Windows named pipe). Of these only
  62. the first is guaranteed to be available.
  63. If `family` is `None` than the family is inferred from the
  64. format of `address`. If `address` is also `None` then a
  65. default is chosen. This default is the family which is
  66. assumed to be the fastest available. See `Address
  67. formats`_.
  68. Note that if `family` is `'AF_UNIX'` then the associated
  69. file will have only be readable/writable by the user
  70. running the current process -- use `os.chmod()` is you need
  71. to let other users access the socket.
  72. `backlog`
  73. If the listener object uses a socket then `backlog` is
  74. passed to the `listen()` method of the socket once it has
  75. been bound.
  76. `authenticate`
  77. If `authenticate` is true or `authkey` is not `None` then
  78. digest authentication is used.
  79. `authkey`
  80. If `authkey` is a string then it will be used as the
  81. authentication key; otherwise it must be `None`.
  82. If `authkey` is `None` and `authenticate` is true then
  83. `currentProcess.getAuthKey()` is used as the authentication
  84. key.
  85. If `authkey` is `None` and `authentication` is false then
  86. no authentication is done.
  87. If authentication fails then `AuthenticationError` is
  88. raised. See `Authentication keys`_.
  89. `accept()`
  90. Accept a connection on the bound socket or named pipe of the
  91. listener object. If authentication is attempted and fails
  92. then `AuthenticationError` is raised.
  93. Returns a `connection object <connection-object.html>` object.
  94. `close()`
  95. Close the bound socket or named pipe of the listener object.
  96. This is called automatically when the listener is garbage
  97. collected. However it is advisable to call it explicitly.
  98. Listener objects have the following read-only properties:
  99. `address`
  100. The address which is being used by the listener object.
  101. `last_accepted`
  102. The address from which the last accepted connection came.
  103. If this is unavailable then `None` is returned.
  104. Address formats
  105. ===============
  106. * An `'AF_INET'` address is a tuple of the form `(hostname, port)`
  107. where `hostname` is a string and `port` is an integer
  108. * An `'AF_UNIX'` address is a string representing a filename on the
  109. filesystem.
  110. * An `'AF_PIPE'` address is a string of the form
  111. `r'\\\\.\\pipe\\PipeName'`.
  112. To use `Client` to connect to a named pipe on a remote computer
  113. called `ServerName` one should use an address of the form
  114. `r'\\\\ServerName\\pipe\\PipeName'` instead.
  115. Note that any string beginning with two backslashes is assumed by
  116. default to be an `'AF_PIPE'` address rather than an `'AF_UNIX'`
  117. address.
  118. Authentication keys
  119. ===================
  120. When one uses the `recv()` method of a connection object, the data
  121. received is automatically unpickled. Unfortunately unpickling data
  122. from an untrusted source is a security risk. Therefore `Listener` and
  123. `Client` use the `hmac` module to provide digest authentication.
  124. An authentication key is a string which can be thought of as a
  125. password: once a connection is established both ends will demand proof
  126. that the other knows the authentication key. (Demonstrating that both
  127. ends are using the same key does *not* involve sending the key over
  128. the connection.)
  129. If authentication is requested but do authentication key is specified
  130. then the return value of `currentProcess().getAuthKey()` is used (see
  131. `Process objects <process-objects.html>`_). This value will
  132. automatically inherited by any `Process` object that the current
  133. process creates. This means that (by default) all processes of a
  134. multi-process program will share a single authentication key which can
  135. be used when setting up connections between the themselves.
  136. Suitable authentication keys can also be generated by using
  137. `os.urandom()`.
  138. Example
  139. =======
  140. The following server code creates a listener which uses `'secret
  141. password'` as an authentication key. It then waits for a connection
  142. and sends some data to the client::
  143. from processing.connection import Listener
  144. from array import array
  145. address = ('localhost', 6000) # family is deduced to be 'AF_INET'
  146. listener = Listener(address, authkey='secret password')
  147. conn = listener.accept()
  148. print 'connection accepted from', listener.last_accepted
  149. conn.send([2.25, None, 'junk', float])
  150. conn.sendBytes('hello')
  151. conn.sendBytes(array('i', [42, 1729]))
  152. conn.close()
  153. listener.close()
  154. The following code connects to the server and receives some data from
  155. the server::
  156. from processing.connection import Client
  157. from array import array
  158. address = ('localhost', 6000)
  159. conn = Client(address, authkey='secret password')
  160. print conn.recv() # => [2.25, None, 'junk', float]
  161. print conn.recvBytes() # => 'hello'
  162. arr = array('i', [0, 0, 0, 0, 0])
  163. print conn.recvBytesInto(arr) # => 8
  164. print arr # => array('i', [42, 1729, 0, 0, 0])
  165. conn.close()
  166. .. _Prev: sharedctypes.html
  167. .. _Up: processing-ref.html
  168. .. _Next: programming-guidelines.html