Package core :: Module net

[hide private]
[frames] | no frames]

# Source Code for Module core.net

      1  # Copyright 2011 the original author or authors.
      2  #
      3  # Licensed under the Apache License, Version 2.0 (the "License");
      4  # you may not use this file except in compliance with the License.
      5  # You may obtain a copy of the License at
      6  #
      7  #      http://www.apache.org/licenses/LICENSE-2.0
      8  #
      9  # Unless required by applicable law or agreed to in writing, software
     10  # distributed under the License is distributed on an "AS IS" BASIS,
     11  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12  # See the License for the specific language governing permissions and
     13  # limitations under the License.
     14
     15  """
     16  Net support to the python vert.x platform
     17  """
     18
     19  import org.vertx.java.core.Handler
     20  import org.vertx.java.deploy.impl.VertxLocator
     21  import core.tcp_support
     22  import core.ssl_support
     23  import core.buffer
     24  import core.streams
     25
     26  from core.handlers import CloseHandler, DoneHandler, ClosedHandler
     27  from core.event_bus import EventBus
     28
     29  __author__ = "Scott Horn"
     30  __email__ = "scott@hornmicro.com"
     31  __credits__ = "Based entirely on work by Tim Fox http://tfox.org"
     32
     33 -class NetServer(core.ssl_support.SSLSupport, core.tcp_support.TCPSupport):
     34      """Represents a TCP or SSL Server
     35
     36      When connections are accepted by the server
     37      they are supplied to the user in the form of a NetSocket instance that is passed via the handler
     38      set using connect_handler.
     39      """
     40 -    def __init__(self, **kwargs):
     41          self.java_obj = org.vertx.java.deploy.impl.VertxLocator.vertx.createNetServer()
     42          for item in kwargs.keys():
     43             setattr(self, item, kwargs[item])
     44
     45 -    def set_client_auth_required(self, val):
     46          """Client authentication is an extra level of security in SSL, and requires clients to provide client certificates.
     47          Those certificates must be added to the server trust store.
     48          @param val:  If true then the server will request client authentication from any connecting clients, if they
     49          do not authenticate then they will not make a connection.
     50          """
     51          self.java_obj.setClientAuthRequired(val)
     52          return self
     53      client_auth_required = property(fset=set_client_auth_required)
     54
     55 -    def connect_handler(self, handler):
     56          """Supply a connect handler for this server. The server can only have at most one connect handler at any one time.
     57          As the server accepts TCP or SSL connections it creates an instance of NetSocket and passes it to the
     58          connect handler.
     59
     60          Keyword arguments:
     61          @param handler: connection handler
     62
     63          @return: a reference to self so invocations can be chained
     64          """
     65          self.java_obj.connectHandler(ConnectHandler(handler))
     66          return self
     67
     68
     69 -    def listen(self, port, host="0.0.0.0"):
     70          """Instruct the server to listen for incoming connections.
     71
     72          Keyword arguments:
     73          @param port: The port to listen on.
     74          @param host: The host name or ip address to listen on.
     75
     76          @return: a reference to self so invocations can be chained
     77          """
     78          self.java_obj.listen(port, host)
     79          return self
     80
     81
     82 -    def close(self, handler=None):
     83          """Close the server. The handler will be called when the close is complete."""
     84          self.java_obj.close(CloseHandler(handler))
     85
     86
     87
     88 -class NetClient(core.ssl_support.SSLSupport, core.tcp_support.TCPSupport):
     89      """NetClient is an asynchronous factory for TCP or SSL connections.
     90
     91      Multiple connections to different servers can be made using the same instance.
     92      """
     93 -    def __init__(self, **kwargs):
     94          self.java_obj = org.vertx.java.deploy.impl.VertxLocator.vertx.createNetClient()
     95          for item in kwargs.keys():
     96             setattr(self, item, kwargs[item])
     97
     98 -    def set_trust_all(self, val):
     99          """Should the client trust ALL server certificates
    100
    101          Keyword arguments:
    102          @param val:  If val is set to true then the client will trust ALL server certificates and will not attempt to authenticate them
    103          against it's local client trust store. The default value is false.
    104
    105          Use this method with caution!
    106
    107          @return: a reference to self so invocations can be chained
    108          """
    109          self.java_obj.setTrustAll(val)
    110          return self
    111
    112      trust_all = property(fset=set_trust_all)
    113
    114 -    def connect(self, port, host, handler):
    115          """Attempt to open a connection to a server. The connection is opened asynchronously and the result returned in the
    116          handler.
    117
    118          Keyword arguments:
    119          @param port: The port to connect to.
    120          @param host: The host or ip address to connect to.
    121          @param handler: The connection handler
    122
    123          @return: a reference to self so invocations can be chained
    124          """
    125          self.java_obj.connect(port, host, ConnectHandler(handler))
    126          return self
    127
    128 -    def close(self):
    129          """Close the NetClient. Any open connections will be closed."""
    130          self.java_obj.close()
    131
    132 -class NetSocket(core.streams.ReadStream, core.streams.WriteStream):
    133      """NetSocket is a socket-like abstraction used for reading from or writing
    134      to TCP connections.
    135      """
    136 -    def __init__(self, j_socket):
    137          self.java_obj = j_socket
    138
    139          def simple_handler(msg):
    140              self.write_buffer(msg.body)
    141
    142          self.write_handler_id = EventBus.register_simple_handler(False, simple_handler)
    143
    144          def wrapped_closed_handler():
    145              EventBus.unregister_handler(self.write_handler_id)
    146              if hasattr(self, "_closed_handler"):
    147                  self._closed_handler()
    148          self.java_obj.closedHandler(ClosedHandler(wrapped_closed_handler))
    149
    150 -    def write_buffer(self, buffer, handler=None):
    151          """Write a Buffer to the socket. The handler will be called when the buffer has actually been written to the wire.
    152
    153          Keyword arguments:
    154          @param buffer: The buffer to write.
    155          @param handler: The handler to call on completion.
    156          """
    157          java_buffer = buffer._to_java_buffer()
    158          if handler is None:
    159              self.java_obj.write(java_buffer)
    160          else:
    161              self.java_obj.write(java_buffer, DoneHandler(handler))
    162
    163 -    def write_str(self, str, enc="UTF-8", handler=None):
    164          """Write a String to the socket. The handler will be called when the string has actually been written to the wire.
    165
    166          Keyword arguments:
    167          @param str: The string to write.
    168          @param enc: The encoding to use.
    169          @param handler: The handler to call on completion.
    170          """
    171          if handler is None:
    172              self.java_obj.write(str, enc)
    173          else:
    174              self.java_obj.write(str, enc, DoneHandler(handler))
    175
    176 -    def closed_handler(self, handler):
    177          """Set a closed handler on the socket.
    178
    179          Keyword arguments:
    180          @param handler: A block to be used as the handler
    181          """
    182          self._closed_handler = handler
    183
    184 -    def send_file(self, file_path):
    185          """Tell the kernel to stream a file directly from disk to the outgoing connection, bypassing userspace altogether
    186          (where supported by the underlying operating system. This is a very efficient way to stream files.
    187
    188          Keyword arguments:
    189          @param file_path: Path to file to send.
    190          """
    191          self.java_obj.sendFile(file_path)
    192
    193 -    def close(self):
    194          """Close the socket"""
    195          self.java_obj.close()
    196
    197 -class ConnectHandler(org.vertx.java.core.Handler):
    198      """ Connection handler """
    199 -    def __init__(self, handler):
    200          self.handler = handler
    201
    202 -    def handle(self, socket):
    203          """ Call the handler after connection is established"""
    204          self.handler(NetSocket(socket))
    205