1 # Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
17 Module defines protocol based classes and utils.
20 from abc import ABCMeta
21 from abc import abstractmethod
25 @six.add_metaclass(ABCMeta)
26 class Protocol(object):
27 """Interface for various protocols.
29 Protocol usually encloses a transport/connection/socket to
30 peer/client/server and encodes and decodes communication/messages. Protocol
31 can also maintain any related state machine, protocol message encoding or
32 decoding utilities. This interface identifies minimum methods to support to
33 facilitate or provide hooks to sub-classes to override behavior as
38 def data_received(self, data):
39 """Handler for date received over connection/transport.
41 Here *data* is in raw bytes. This *data* should further be converted to
42 protocol specific messages and as appropriate transition to new state
43 machine state or send appropriate response.
48 def connection_made(self):
49 """Called when connection has been established according to protocol.
51 This is the right place to do some initialization or sending initial
57 def connection_lost(self, reason):
58 """Handler called when connection to peer/remote according to protocol
61 Here we can do any clean-up related to connection/transport/timers/etc.
66 @six.add_metaclass(ABCMeta)
67 class Factory(object):
68 """This is a factory which produces protocols.
70 Can also act as context for protocols.
73 # Put a subclass of Protocol here:
77 def build_protocol(self, socket):
78 """Create an instance of a subclass of Protocol.
80 Override this method to alter how Protocol instances get created.
82 raise NotImplementedError()
85 def start_protocol(self, socket):
86 """Launch protocol instance to handle input on an incoming connection.
88 raise NotImplementedError()