本文整理匯總了Python中transport.Transport.close方法的典型用法代碼示例。如果您正苦於以下問題:Python Transport.close方法的具體用法?Python Transport.close怎麽用?Python Transport.close使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類transport.Transport
的用法示例。
在下文中一共展示了Transport.close方法的6個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: Main
# 需要導入模塊: from transport import Transport [as 別名]
# 或者: from transport.Transport import close [as 別名]
class Main(object):
def __init__(self):
self.monitor = None
try:
# instanciates the config
self.config = Config()
# exists baboon when receiving a sigint signal
signal.signal(signal.SIGINT, self.sigint_handler)
# Initialize the scm class to use
scm_classes = Diffman.__subclasses__()
for cls in scm_classes:
tmp_inst = cls()
if tmp_inst.scm_name == self.config.scm:
self.diffman = tmp_inst
# TODO verify self.diffman
self.mediator = Mediator(self.diffman)
self.transport = Transport(self.mediator)
self.transport.open()
self.monitor = Monitor(self.transport, self.diffman)
self.monitor.watch()
# TODO this won't work on windows...
signal.pause()
except BaboonException, err:
sys.stderr.write("%s\n" % err)
# Try to close the transport properly. If the transport is
# not correctly started, the close() method has no effect.
self.transport.close()
# Same thing for the monitor
if self.monitor:
self.monitor.close()
# Exits with a fail return code
sys.exit(1)
示例2: Player
# 需要導入模塊: from transport import Transport [as 別名]
# 或者: from transport.Transport import close [as 別名]
class Player(object):
auth_timeout = 5
def __init__(self, socket, address):
self.transport = Transport(socket, address)
self.host = address[0]
self.port = address[1]
self.health = 100
def close(self):
self.transport.send(Message.exit().pack())
self.transport.close()
def auth(self):
recv = None
with Timeout(Player.auth_timeout, PlayerError("Authentication timed out")):
try:
msg = self.transport.receive()
except PlayerError as e:
print("error on receive")
print(e)
return False
try:
msg = Message.parse(msg)
except MessageError:
print("bad message")
return False
if msg.type == "nick":
self.name = msg.payload
self.transport.send(Message.auth_success().pack())
return True
return False
def listen(self):
return self.transport.receive()
def send(self, msg):
self.transport.send(msg)
示例3: ServerConnection
# 需要導入模塊: from transport import Transport [as 別名]
# 或者: from transport.Transport import close [as 別名]
class ServerConnection(object):
def __init__(self, host, port, key, app, service, topic, lang, format, logger=None, punctuation=True):
self.host = host
self.port = port
self.key = key
self.app = app
self.topic = topic
self.service = service
self.lang = lang
self.format = format
self.uuid = randomUuid().hex
self.logger = logger
self.punctuation = punctuation
self.log("uuid={0}".format(self.uuid))
self.session_id = ""
self.connect()
def log(self, message):
if self.logger is not None:
self.logger.info(message)
def connect(self):
self.t = Transport(self.host, self.port, timeout=None, verbose=False)
if not self.upgrade_connection():
raise ServerError('Unable to upgrade connection')
self.log("Connected to {0}:{1}.".format(self.host, self.port))
response = self.send_init_request()
if response.responseCode != 200:
error_text = 'Wrong response from server, status_code={0}'.format(
response.responseCode)
if response.HasField("message"):
error_text += ', message is "{0}"'.format(response.message)
raise ServerError(error_text)
self.session_id = response.sessionId
self.log("session_id={0}".format(self.session_id))
return self.session_id
def send_init_request(self):
request = ConnectionRequest(
speechkitVersion='Not Speechkit',
serviceName=self.service,
uuid=self.uuid,
apiKey=self.key,
applicationName=self.app,
device='desktop',
coords='0, 0',
topic=self.topic,
lang=self.lang,
format=self.format,
punctuation=self.punctuation)
self.t.sendProtobuf(request)
return self.t.recvProtobuf(ConnectionResponse)
def upgrade_connection(self):
logger = logging.getLogger('arslib')
request = ('GET /asr_partial_checked HTTP/1.1\r\n'
'User-Agent: {user_agent}\r\n'
'Host: {host}:{port}\r\n'
'Upgrade: {service}\r\n\r\n').format(
user_agent=self.app,
host=self.host,
port=self.port,
service=self.service)
self.t.send(request)
check = 'HTTP/1.1 101 Switching Protocols'
buffer = ''
# possible infinite loop here?
while True:
buffer += self.t.recv(1)
if buffer.startswith(check) and buffer.endswith('\r\n\r\n'):
return True
if len(buffer) > 300:
logger.warning(buffer)
return False
def close(self):
self.session_id = ""
self.t.close()
def reconnect(self, delay=None):
self.log('Reconnecting!')
self.close()
if delay is not None:
self.log('Going to sleep for {0} seconds'.format(delay))
time.sleep(delay)
self.connect()
def add_data(self, chunk):
if chunk is None:
self.t.sendProtobuf(AddData(lastChunk=True))
#.........這裏部分代碼省略.........
示例4: ServerConnection
# 需要導入模塊: from transport import Transport [as 別名]
# 或者: from transport.Transport import close [as 別名]
class ServerConnection(object):
def __init__(self, host, port, key, app, service, topic, lang, format, uuid, inter_utt_silence, cmn_latency, logger=None, punctuation=True, ipv4=False, capitalize=False, expected_num_count=0):
self.host = host
self.port = port
self.key = key
self.app = app
self.topic = topic
self.service = service
self.lang = lang
self.format = format
self.uuid = uuid
self.logger = logger
self.punctuation = punctuation
self.inter_utt_silence = inter_utt_silence
self.cmn_latency = cmn_latency
self.ipv4 = ipv4
self.capitalize = capitalize
self.expected_num_count = expected_num_count
self.log("uuid={0}".format(self.uuid))
self.session_id = "not-set"
self.connect()
def log(self, message):
if self.logger is not None:
self.logger.info(message)
def connect(self):
self.t = Transport(self.host, self.port, timeout=None, verbose=False, enable_ssl=(self.port==443), ipv4=self.ipv4)
if not self.upgrade_connection():
raise ServerError('Unable to upgrade connection')
self.log("Connected to {0}:{1}.".format(self.host, self.port))
response = self.send_init_request()
if response.responseCode != 200:
error_text = 'Wrong response from server, status_code={0}'.format(
response.responseCode)
if response.HasField("message"):
error_text += ', message is "{0}"'.format(response.message)
raise ServerError(error_text)
self.session_id = response.sessionId
self.log("session_id={0}".format(self.session_id))
return self.session_id
def send_init_request(self):
request = ConnectionRequest(
speechkitVersion='',
serviceName=self.service,
uuid=self.uuid,
apiKey=self.key,
applicationName=self.app,
device='desktop',
coords='0, 0',
topic=self.topic,
lang=self.lang,
format=self.format,
punctuation=self.punctuation,
advancedASROptions=AdvancedASROptions(
utterance_silence=int(self.inter_utt_silence),
cmn_latency=self.cmn_latency,
capitalize=self.capitalize,
expected_num_count=self.expected_num_count,
biometry="children",
)
)
self.t.sendProtobuf(request)
return self.t.recvProtobuf(ConnectionResponse)
def upgrade_connection(self):
logger = logging.getLogger('arslib')
request = ('GET /asr_partial_checked HTTP/1.1\r\n'
'User-Agent: {user_agent}\r\n'
'Host: {host}:{port}\r\n'
'Upgrade: {service}\r\n\r\n').format(
user_agent=self.app,
host=self.host,
port=self.port,
service=self.service)
self.t.send(request)
check = 'HTTP/1.1 101 Switching Protocols'
buffer = ''
# possible infinite loop here?
while True:
buffer += self.t.recv(1)
if buffer.startswith(check) and buffer.endswith('\r\n\r\n'):
return True
if len(buffer) > 300:
logger.warning(buffer)
return False
def close(self):
self.session_id = ""
#.........這裏部分代碼省略.........
示例5: MicroNFCBoard
# 需要導入模塊: from transport import Transport [as 別名]
# 或者: from transport.Transport import close [as 別名]
class MicroNFCBoard(object):
@staticmethod
def getBoard(number = 0):
a = INTERFACE[usb_backend].getAllConnectedInterface(VID, PID)
if((a != None) and (len(a) > number)):
return MicroNFCBoard(a[number])
return None
@staticmethod
def getAllBoards():
return [MicroNFCBoard(i) for i in INTERFACE[usb_backend].getAllConnectedInterface(VID, PID)]
def __init__(self, intf):
self._intf = intf
self._transport = Transport()
self._id = None
self._version = None
self._polling = False
self._connected = False
self._ndefMessagePresent = False
self._ndefRecords = None
self._ndefRead = False
def open(self):
self._transport.open(self._intf)
version, revision, self._id = self._transport.info()
self._version = (version, revision)
def close(self):
self._transport.close()
@property
def id(self):
return self._id
@property
def connected(self):
self._updateStatus()
return self._connected
@property
def polling(self):
self._updateStatus()
return self._polling
@property
def ndefMessagePresent(self):
self._updateStatus()
return self._ndefMessagePresent
@property
def ndefRecords(self):
self._updateStatus()
if self._ndefMessagePresent and not self._ndefRead:
self._ndefRecords = self._getNdefMessageRecords()
self._ndefRecordsRead = True
return self._ndefRecords
@property
def version(self):
return self._version
def getNfcInfo(self):
return self._transport.nfcGetInfo()
def reset(self):
self._transport.reset(False)
def startPolling(self):
self._transport.nfcPoll(True)
def stopPolling(self):
self._transport.nfcPoll(True)
def setLeds(self, led1, led2):
self._transport.leds(led1, led2)
def _updateStatus(self):
status = self._transport.status()
self._polling = (status & STATUS_POLLING) != 0
self._connected = (status & STATUS_CONNECTED) != 0
self._ndefMessagePresent = (status & STATUS_NDEF_PRESENT) != 0
if not self._ndefMessagePresent:
self._ndefRecordsRead = False
def _getNdefRecords(self, start, count):
records = []
for recordNumber in range(start, start+count):
#Get records info
recordType, recordInfo = self._transport.nfcGetRecordInfo(recordNumber)
funcs = { 0 : self._parseUnknownRecord,
1 : self._parseURIRecord,
2 : self._parseTextRecord,
3 : self._parseSmartPosterRecord,
4 : self._parseMIMERecord,
}
record = funcs[recordType](recordNumber, recordInfo)
if record != None:
records += [record]
return records
#.........這裏部分代碼省略.........
示例6: MicroNFCBoard
# 需要導入模塊: from transport import Transport [as 別名]
# 或者: from transport.Transport import close [as 別名]
class MicroNFCBoard(object):
@staticmethod
def getBoard(number = 0):
a = INTERFACE[usb_backend].getAllConnectedInterface(VID, PID)
if((a != None) and (len(a) > number)):
return MicroNFCBoard(a[number])
return None
@staticmethod
def getAllBoards():
return [MicroNFCBoard(i) for i in INTERFACE[usb_backend].getAllConnectedInterface(VID, PID)]
def __init__(self, intf):
self._intf = intf
self._transport = Transport()
self._id = None
self._version = None
self._polling = False
self._connected = False
self._type2 = False
self._type4 = False
self._p2p = False
self._initiator = False
self._ndefPresent = False
self._ndefRecords = None
self._ndefRead = False
self._ndefReadable = False
self._ndefWriteable = False
self._ndefBusy = False
self._ndefSuccess = False
def open(self):
self._transport.open(self._intf)
version, revision, self._id = self._transport.info()
self._version = (version, revision)
if( self._version < TARGET_FIRMWARE ):
#self._transport.reset(True)
raise FirmwareUpgradeRequiredException("Your current firmware (version %d.%d) is outdated; please upgrade it to version %d.%d" % (version, revision, TARGET_FIRMWARE[0], TARGET_FIRMWARE[1]))
def close(self):
self._transport.close()
@property
def id(self):
return self._id
@property
def connected(self):
self._updateStatus()
return self._connected
@property
def type2Tag(self):
self._updateStatus()
return self._type2 and self._initiator
@property
def type4Emulator(self):
self._updateStatus()
return self._type4 and not self._initiator
@property
def p2p(self):
self._updateStatus()
return self._p2p
@property
def polling(self):
self._updateStatus()
return self._polling
@property
def ndefReadable(self):
self._updateStatus()
return self._ndefReadable
@property
def ndefWriteable(self):
self._updateStatus()
return self._ndefWriteable
@property
def ndefPresent(self):
self._updateStatus()
return self._ndefPresent
@property
def ndefBusy(self):
self._updateStatus()
return self._ndefBusy
@property
def ndefSuccess(self):
self._updateStatus()
return self._ndefSuccess
@property
def ndefRecords(self):
self._updateStatus()
if self._ndefPresent and not self._ndefRead:
#.........這裏部分代碼省略.........