__init__.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. #!/usr/bin/env python3.5
  2. # Copyright 2017 Digital
  3. #
  4. # This file is part of DigiLib.
  5. #
  6. # DigiLib is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # DigiLib is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with DigiLib. If not, see <http://www.gnu.org/licenses/>.
  18. import atexit
  19. import logging
  20. import logging.handlers
  21. import os
  22. import queue
  23. import select
  24. import socket
  25. import sys
  26. import threading
  27. import time
  28. import traceback
  29. import blinker
  30. import curio
  31. import digilib.misc
  32. lclient = logging.getLogger(__name__+".client")
  33. lserver = logging.getLogger(__name__+".server")
  34. lch = logging.getLogger(__name__+".chandler")
  35. lschat = logging.getLogger(__name__+".server.chat")
  36. lcchat = logging.getLogger(__name__+".client.chat")
  37. _tasks = []
  38. class ConnHandlerBase(object):
  39. """
  40. ConnectionHandlerBase is the base class for all connection handlers.
  41. It provides basic methodes. Consider inheriting form ConnectionHandler
  42. instead, as it provides better functionality.
  43. """
  44. addr = None
  45. block_size = 1024
  46. server = None
  47. def __init__(self, socket, addr, server):
  48. super(ConnHandlerBase, self).__init__()
  49. self.socket = socket
  50. self.addr = addr
  51. self.server = server
  52. async def disconnect(self):
  53. """
  54. disconenct explicitely disconnects the client, shuts the socket down
  55. and closes it.
  56. """
  57. try:
  58. await self.send(bytes())
  59. except:
  60. lch.debug("error during disconenct")
  61. try:
  62. await self.socket.shutdown(0)
  63. except:
  64. lch.debug("error during socket shutdown")
  65. try:
  66. await self.socket.close()
  67. except:
  68. lch.debug("error closing socket")
  69. async def handle(self, data):
  70. """
  71. This method is called for every message the server receives from the
  72. client. It should handle the data. Performing asynchronous blocking
  73. actions is ok, as the client loop does not wait for this method to
  74. finish. therefore, this method can be called multiple times at once,
  75. use curio locks if appropriate.
  76. """
  77. raise NotImplemented()
  78. async def recv(self,block_size=block_size):
  79. """
  80. This method waits for the client to send something and returns bytes!
  81. """
  82. data_received = await self.socket.recv(self,self.block_size)
  83. return data_received
  84. async def send(self, data, log_msg=None):
  85. """
  86. This method sends bytes to the client. Returns False if an exception
  87. was raised during sending, otherwise True.
  88. """
  89. if log_msg:
  90. lschat.info("server:"+str(log_msg))
  91. else:
  92. lschat.info("Server:"+str(data))
  93. try:
  94. await self.socket.send(data)
  95. return True
  96. except Exception as e:
  97. lch.error(e, exc_info=True)
  98. return False
  99. class ConnHandler(ConnHandlerBase):
  100. """
  101. More advanced connection handler than ConnectionHandlerBase. For
  102. instance, sends() takes a string and encodes it, recv() decodes
  103. the client's and returns a string and welcome_client is called after
  104. the ConnHandler is initialized (Not after the inheriting class is
  105. initialized though!)
  106. """
  107. def __init__(self, socket, addr, server):
  108. super(ConnHandler, self).__init__(socket,addr,server)
  109. async def disconnect(self):
  110. """
  111. disconenct() explicitely disconnects the client, performes a proper
  112. the shutdow on the socket and closes it.
  113. """
  114. try:
  115. await self.send("")
  116. except:
  117. lch.debug("error during disconenct")
  118. try:
  119. await self.socket.shutdown(0)
  120. except:
  121. lch.debug("error during socket shutdown")
  122. try:
  123. await self.socket.close()
  124. except:
  125. lch.debug("error closing socket")
  126. async def handle(self, data):
  127. return
  128. async def on_welcome(self):
  129. """
  130. This method can be used to send a welcome message to the client.
  131. """
  132. self.send("Welcome client, this is the server sending!")
  133. async def recv(self,block_size=None):
  134. """
  135. This method waits for the client to send something, decodes it and
  136. returns a string.
  137. """
  138. if block_size == None:
  139. block_size = self.block_size
  140. lch.debug("self.__class__: {}".format(self.__class__))
  141. data_received = await super().recv(self,block_size=block_size)
  142. data_decoded = data_received.decode("utf-8")
  143. return data_decoded
  144. async def send(self, data, log_msg=False):
  145. """
  146. This method takes a string, encodes it and sends it to the client.
  147. Returns False if an exception was raised during sending, otherwise True.
  148. """
  149. if log_msg:
  150. lschat.info("server:"+log_msg)
  151. else:
  152. lschat.info("Server:"+data)
  153. data_encoded = bytes(data, "utf-8")
  154. send_status = await super().send(data_encoded)
  155. return send_status
  156. class ConnHandlerEcho(ConnHandler):
  157. """
  158. A Conn handler which sends everything it receives to every other client
  159. connected to the server
  160. """
  161. def __init__(self, socket, addr, server):
  162. super(ConnHandlerEcho, self).__init__(socket, addr, server)
  163. def handle(self, data):
  164. for h in self.server.connection_handler:
  165. if not h is self:
  166. h.send(data)
  167. class Server(object):
  168. """
  169. Server opens either an unix or an inet connection. For every new client
  170. a new ClientHandler object is created.
  171. _string_ **host** and _int_ **port** are the filename, hostname or ip
  172. address and the port respectively on which the connection will be opened.
  173. If you make an AF_UNIX socket, port is ignored so simply pass None.
  174. _object_ **handler_class** is the class (not an object of the class) used
  175. for making connection handlers.
  176. _dict_ **handler_kwargs** is a dict which will be passed as keyword
  177. argumetns to the __init__ function of handler_class when creating a new
  178. connection handler. Default is an emtpy dict.
  179. _string_ **af_family** specifies the AF_FAMILY socket type, valid options
  180. are: "AF_INET" for a inet socket and "AF_UNIX" for a unix (file) socket.
  181. Default is "AF_INET".
  182. _bool_ **log_ip** specifies wether the ip address of the server/client is logged.
  183. Default is False.
  184. _int_ **max_allowed_clients** specifies the maximum amount of clients
  185. connected to the server at once. Default is 5 (for now. this will change
  186. in the future).
  187. """
  188. # set to true when the server shuts down, for instance after a
  189. # fatal exception
  190. exit_event = False
  191. def __init__(self,
  192. host,
  193. port,
  194. handler_class,
  195. handler_kwargs={},
  196. af_family="AF_INET",
  197. log_ip=False,
  198. max_allowed_clients=5,
  199. ):
  200. super(Server, self).__init__()
  201. self.host = host
  202. self.port = port
  203. self.handler_class = handler_class
  204. self.handler_kwargs = handler_kwargs
  205. self.af_family = af_family
  206. self.log_ip = log_ip
  207. self.max_allowed_clients = max_allowed_clients
  208. # don't make the socket yet, we don't need right now. will be created
  209. # when the start method is called
  210. self.socket = None
  211. # create a task group for handlers, so we can easily cancel/terminate
  212. # them all at once
  213. self.handle_tasks = curio.TaskGroup(name="tg_handle_clients")
  214. # list of all active connection handlers
  215. self.connection_handler = []
  216. # register our cleanup method to be executed when the program exits.
  217. # the cleanup function unregisters itself, so it won't get executed twice when the user called it befor the program exites
  218. atexit.register(self.shutdown)
  219. def make_socket(self):
  220. """
  221. factory method for sockets.
  222. this method makes a normal socket and wraps it in a curi.io.Socket wrapper
  223. """
  224. lserver.debug("making a {} socket".format(self.af_family))
  225. if self.af_family == "AF_INET":
  226. s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  227. elif self.af_family == "AF_UNIX":
  228. s = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
  229. else:
  230. raise ValueError(
  231. "AF_FAMILY '{}' not supported!".format(
  232. self.af_family
  233. )
  234. )
  235. s = curio.io.Socket(s)
  236. return s
  237. def make_handler(self, conn, addr):
  238. """
  239. factory method for handlers.
  240. this method creates a handler object from self.handler_class and self.handler_kwargs
  241. """
  242. return self.handler_class(conn, addr, self, **self.handler_kwargs)
  243. def setup(self):
  244. """
  245. creates a scoket, opens the connection and starts listening for
  246. clients. this method does not block, it returns after starting to
  247. listen.
  248. """
  249. lserver.info("setting up server")
  250. self.socket = self.make_socket()
  251. if self.af_family == "AF_INET":
  252. self.socket.bind((self.host, self.port))
  253. elif self.af_family == "AF_UNIX":
  254. if os.path.exists(self.host):
  255. lserver.debug("file already exists")
  256. lserver.debug("attempting to remove it")
  257. os.remove(self.host)
  258. self.socket.bind(self.host)
  259. self.socket.listen(self.max_allowed_clients)
  260. def shutdown(self):
  261. """
  262. This method properly shuts down the sockets and closes them.
  263. it unregisters itself from atexit, so it doesn't get executed twice
  264. when it was manually called before to program exits.
  265. """
  266. def error_handler(func,*args,log_text="error",async_=False,**kwargs):
  267. try:
  268. if async_:
  269. coro = func(*args,**kwargs)
  270. lserver.debug("{} {}".format(func,coro))
  271. else:
  272. func(*args,**kwargs)
  273. except Exception as exc:
  274. lserver.debug("error occured during "+log_text,exc_info=exc)
  275. atexit.unregister(self.shutdown)
  276. lserver.info("shutting down server")
  277. error_handler(
  278. self.handle_tasks.cancel_remaining,log_text="handler cancel",async_=True)
  279. # check if there is actually a socket. if the shutdown method is
  280. # executed before the start method, there is no socket.
  281. if self.socket:
  282. error_handler(self.socket.shutdown,log_text="socket shutdown")
  283. error_handler(self.socket.close,log_text="socket close")
  284. def start(self):
  285. """
  286. this method starts the server. it is blocking.
  287. """
  288. self.setup()
  289. curio.run(self.run)
  290. async def run(self):
  291. """
  292. this method is the main loop of the Server. it waits for new client
  293. connections and creates a handle task for each of them. it does not
  294. receive or send anything.
  295. """
  296. lserver.debug("entering main loop")
  297. while ( not self.exit_event ):
  298. lserver.debug("waiting for client to connect")
  299. # wait for a client to connect
  300. conn,addr = await self.socket.accept()
  301. if self.log_ip:
  302. lserver.info(
  303. "new client connection, {}:{}!".format(*addr))
  304. else:
  305. lserver.info("a new client connected, let's handle it")
  306. handler = self.make_handler(conn, addr)
  307. # self.register_conn(conn, addr)
  308. # self.register_handler(handler, conn)
  309. await self.handle_tasks.spawn(self.handle_client(conn,handler))
  310. async def handle_client(self,socket,handler):
  311. """
  312. This method waits for the client to send something and calls the
  313. ClientHandler's handle method. there is a handle_client method running for each client connected.
  314. """
  315. if hasattr(handler,"on_welcome"):
  316. await handler.on_welcome()
  317. while True:
  318. try:
  319. if self.log_ip:
  320. lserver.debug("waiting for {} to send something"
  321. .format(socket.getsockname()))
  322. else:
  323. lserver.debug("waiting for the client to send something")
  324. # wait for the client to send something
  325. data = await handler.recv()
  326. # if there is no data the client disconnected. this is a
  327. # tcp protocoll specification.
  328. if not data:
  329. if self.log_ip:
  330. lserver.info("the connection to {} was closed"
  331. .format(socket.getsockname()))
  332. else:
  333. lserver.info("the connection to the client was closed")
  334. await handler.disconnect()
  335. # break out of the loop. don't return because we need to
  336. # do cleanup
  337. break
  338. else:
  339. # don't strip the data of its whitespaces, since they may
  340. # be important.
  341. lschat.info("Client:"+data.rstrip())
  342. coro = handler.handle(data)
  343. task = await curio.spawn(coro)
  344. except Exception as e:
  345. lserver.error(e, exc_info=True)
  346. # let's sleep a bit, in case something is broken and the
  347. # loop throws an exception every time
  348. await curio.sleep(0.01)
  349. # if a task exits and hasn't been joined, curio prints a warning.
  350. # we don't want the warning, so let's join the current task for 0
  351. # seconds. instead of task.join() we use task.wait(). the only
  352. # difference is that wait doesn't throw a exception if the task was
  353. # stopped or crashed
  354. cur_task = await curio.current_task()
  355. await curio.ignore_after(0,cur_task.wait)
  356. class Client(threading.Thread):
  357. """docstring for Client"""
  358. is_connecting = False
  359. is_connected = False
  360. status = "uninitialized"
  361. def __init__(self,
  362. host,
  363. port=None,
  364. af_family="AF_INET",
  365. handle_data_func=None,
  366. error_handler=None,
  367. block_size=1024,
  368. ):
  369. self.super_class = super(Client, self)
  370. self.super_class.__init__()
  371. self.name = "Client"
  372. self.exit_event = False
  373. self.host = host
  374. self.port = port
  375. self.af_family = af_family
  376. self.block_size = block_size
  377. self.handle_data_func = handle_data_func
  378. self.is_connected = False
  379. self.error_handler = error_handler
  380. # self.socket = self.make_socket()
  381. self.socket = None
  382. self.status = "disconnected"
  383. def connect(self):
  384. self.status = "connecting"
  385. self.socket = self.make_socket()
  386. lclient.info(
  387. "connecting to socket '{}' of type {}".format(
  388. self.host,
  389. self.af_family
  390. )
  391. )
  392. try:
  393. if self.af_family == "AF_INET":
  394. self.socket.connect((self.host, self.port))
  395. elif self.af_family == "AF_UNIX":
  396. if os.path.exists(self.host):
  397. self.socket.connect(self.host)
  398. else:
  399. lclient.warn("File not found. Aborting.")
  400. return
  401. self.is_connected = True
  402. self.status = "connected"
  403. lclient.info("connected")
  404. return True
  405. except Exception as e:
  406. lclient.debug(e, exc_info=True)
  407. if type(e) is ConnectionRefusedError:
  408. lclient.info("failed to connect to socket '{}'".format(self.host))
  409. self.disconnect()
  410. return False
  411. def disconnect(self):
  412. lclient.info("disconnecting from socket '{}'".format(self.host))
  413. self.is_connected = False
  414. self.status = "disconnected"
  415. if self.socket:
  416. try:
  417. self.socket.shutdown(socket.SHUT_RDWR)
  418. except Exception as e:
  419. lclient.error(e)
  420. try:
  421. self.socket.close()
  422. except Exception as e:
  423. lclient.error("error occured while closing the socket, " +
  424. "maybe it is already closed",exc_info=e)
  425. del self.socket
  426. self.socket = None
  427. def handle_data(self, data_received):
  428. data_decoded = data_received.decode("utf-8")
  429. lcchat.info("Server: "+data_decoded)
  430. if self.handle_data_func:
  431. try:
  432. self.handle_data_func(data_decoded)
  433. except Exception as e:
  434. lclient.error(e, exc_info=True)
  435. def is_running(self):
  436. return (self in threading.enumerate())
  437. def make_socket(self):
  438. lclient.info("creating a {} socket".format(self.af_family))
  439. if self.af_family == "AF_INET":
  440. s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  441. elif self.af_family == "AF_UNIX":
  442. s = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
  443. else:
  444. raise ValueError(
  445. "AF_FAMILY '{}' not supported!".format(
  446. self.af_family
  447. )
  448. )
  449. return s
  450. def main_loop(self):
  451. lclient.debug("starting main loop")
  452. while ( not self.exit_event ):
  453. if not self.status in ["connected"]:
  454. time.sleep(0.1)
  455. continue
  456. # print(0)
  457. read_confirmed, write_confirmed, exc_confirmed \
  458. = select.select(
  459. [self.socket],
  460. [],
  461. [self.socket],
  462. 1
  463. )
  464. if self.socket in exc_confirmed:
  465. self.is_connected = False
  466. lclient.warning("socket is expected to corrupt, exiting")
  467. self.disconnect()
  468. # self.stop()
  469. break
  470. elif self.socket in read_confirmed:
  471. try:
  472. data_received = self.read_from_socket()
  473. if data_received == b'':
  474. lclient.info("connection is broken, closing socket exiting")
  475. self.disconnect()
  476. # self.stop()
  477. # break
  478. else:
  479. try:
  480. self.handle_data(data_received)
  481. except Exception as e:
  482. lserver.error(
  483. "Error while handling data",
  484. exc_info=e
  485. )
  486. except Exception as e:
  487. lclient.error(e, exc_info=True)
  488. if type(e) is OSError:
  489. self.is_connected = False
  490. lclient.warn("connection broken, exiting")
  491. self.disconnect()
  492. # self.stop()
  493. # break
  494. else:
  495. raise
  496. else:
  497. time.sleep(0.1)
  498. def read_from_socket(self):
  499. data_received = self.socket.recv(self.block_size)
  500. return data_received
  501. def run(self):
  502. # self.connect()
  503. if self.error_handler:
  504. self.error_handler(self.main_loop)
  505. else:
  506. self.main_loop()
  507. def send(self, msg):
  508. msg = msg.rstrip()
  509. msg_encoded = bytes(msg+"\r\n", "utf-8")
  510. try:
  511. lcchat.info("Client: "+msg)
  512. self.socket.send(msg_encoded)
  513. except Exception as e:
  514. self.is_connected = False
  515. lclient.error(e, exc_info=True)
  516. self.status = "shutdown"
  517. def setup(self):
  518. pass
  519. def stop(self,reason=None):
  520. self.disconnect()
  521. self.exit_event = True
  522. if reason:
  523. print(reason)
  524. class AsyncClient(object):
  525. """docstring for Client"""
  526. is_connecting = False
  527. is_connected = False
  528. status = "uninitialized"
  529. def __init__(self,
  530. host,
  531. port=None,
  532. af_family="AF_INET",
  533. handle_data_func=None,
  534. error_handler=None,
  535. block_size=1024,
  536. ):
  537. self.super_class = super(AsyncClient, self)
  538. self.super_class.__init__()
  539. self.name = "Client"
  540. self.exit_event = False
  541. self.host = host
  542. self.port = port
  543. self.af_family = af_family
  544. self.block_size = block_size
  545. self.handle_data_func = handle_data_func
  546. self.is_connected = False
  547. self.error_handler = error_handler
  548. self.socket = None
  549. self.status = "disconnected"
  550. def connect(self):
  551. self.status = "connecting"
  552. self.socket = self.make_socket()
  553. lclient.info("connecting to socket '{}' of type {}".format(
  554. self.host,self.af_family))
  555. try:
  556. if self.af_family == "AF_INET":
  557. self.socket.connect((self.host, self.port))
  558. elif self.af_family == "AF_UNIX":
  559. self.socket.connect(self.host)
  560. self.is_connected = True
  561. self.status = "connected"
  562. lclient.info("connected")
  563. return True
  564. except Exception as e:
  565. lclient.debug(e, exc_info=True)
  566. if type(e) is ConnectionRefusedError:
  567. lclient.info("failed to connect to socket '{}'".format(self.host))
  568. self.disconnect()
  569. return False
  570. def disconnect(self):
  571. lclient.info("disconnecting from socket '{}'".format(self.host))
  572. self.is_connected = False
  573. self.status = "disconnected"
  574. if self.socket:
  575. try:
  576. self.socket.shutdown(socket.SHUT_RDWR)
  577. except Exception as e:
  578. lclient.error(e)
  579. try:
  580. self.socket.close()
  581. except Exception as e:
  582. lclient.error("error occured while closing the socket, " +
  583. "maybe it is already closed",exc_info=e)
  584. del self.socket
  585. self.socket = None
  586. def handle_data(self, data_received):
  587. data_decoded = data_received.decode("utf-8")
  588. lcchat.info("Server: "+data_decoded)
  589. if self.handle_data_func:
  590. try:
  591. self.handle_data_func(data_decoded)
  592. except Exception as e:
  593. lclient.error(e, exc_info=True)
  594. def is_running(self):
  595. return (self in threading.enumerate())
  596. def make_socket(self):
  597. lclient.info("creating a {} socket".format(self.af_family))
  598. if self.af_family == "AF_INET":
  599. s = trio.socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  600. elif self.af_family == "AF_UNIX":
  601. s = trio.socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
  602. else:
  603. raise ValueError(
  604. "AF_FAMILY '{}' not supported!".format(
  605. self.af_family
  606. )
  607. )
  608. return s
  609. async def read_from_socket(self):
  610. data_received = await self.socket.recv(self.block_size)
  611. return data_received
  612. async def recv(self):
  613. data_received = await self.socket.recv(self.block_size)
  614. data_decoded = data_received.decode("utf-8")
  615. return data_decoded
  616. async def run(self):
  617. lclient.debug("starting main loop")
  618. while ( not self.exit_event ):
  619. if not self.status in ["connected"]:
  620. time.sleep(0.1)
  621. continue
  622. # if self.socket in exc_confirmed:
  623. # self.is_connected = False
  624. # lclient.warning("socket is expected to corrupt, exiting")
  625. # self.disconnect()
  626. # # self.stop()
  627. # break
  628. # elif self.socket in read_confirmed:
  629. try:
  630. data = await self.read_from_socket()
  631. if not data:
  632. lclient.info("connection closed")
  633. self.disconnect()
  634. else:
  635. self.handle_data(data)
  636. except Exception as e:
  637. lclient.error(e, exc_info=True)
  638. if type(e) is OSError:
  639. self.is_connected = False
  640. lclient.warn("connection broken, exiting")
  641. self.disconnect()
  642. else:
  643. raise
  644. async def start(self,connect=False):
  645. if connect:
  646. self.connect()
  647. if self.error_handler:
  648. self.error_handler(self.run)
  649. else:
  650. self.run()
  651. def send(self, msg):
  652. msg = msg.rstrip()
  653. msg_encoded = bytes(msg+"\r\n", "utf-8")
  654. try:
  655. lcchat.info("Client: "+msg)
  656. self.socket.send(msg_encoded)
  657. except Exception as e:
  658. self.is_connected = False
  659. lclient.error(e, exc_info=True)
  660. self.disconnect()
  661. # self.exit_event = True
  662. # self.status = "shutdown"
  663. def setup(self):
  664. pass
  665. def stop(self,reason=None):
  666. self.disconnect()
  667. self.exit_event = True
  668. if reason:
  669. print(reason)
  670. #