__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. lschat = logging.getLogger(__name__+".server.chat")
  35. lcchat = logging.getLogger(__name__+".client.chat")
  36. _tasks = []
  37. class ConnHandlerBase(object):
  38. """
  39. ConnectionHandlerBase is the base class for all connection handlers.
  40. It provides basic methodes. Consider inheriting form ConnectionHandler
  41. instead, as it provides better functionality.
  42. """
  43. addr = None
  44. block_size = 1024
  45. server = None
  46. def __init__(self, socket, addr, server):
  47. super(ConnHandlerBase, self).__init__()
  48. self.socket = socket
  49. self.addr = addr
  50. self.server = server
  51. async def disconnect(self):
  52. """
  53. disconenct explicitely disconnects the client, shuts the socket down
  54. and closes it.
  55. """
  56. try:
  57. await self.send(bytes())
  58. except:
  59. lserver.debug("error during disconenct")
  60. try:
  61. await self.socket.shutdown(0)
  62. except:
  63. lserver.debug("error during socket shutdown")
  64. try:
  65. await self.socket.close()
  66. except:
  67. lserver.debug("error closing socket")
  68. async def handle(self, data):
  69. """
  70. This method is called for every message the server receives from the
  71. client. It should handle the data. Performing asynchronous blocking
  72. actions is ok, as the client loop does not wait for this method to
  73. finish. therefore, this method can be called multiple times at once,
  74. use curio locks if appropriate.
  75. """
  76. raise NotImplemented()
  77. async def recv(self,block_size=block_size):
  78. """
  79. This method waits for the client to send something and returns bytes!
  80. """
  81. data_received = await self.socket.recv(self.block_size)
  82. return data_received
  83. async def send(self, data, log_msg=None):
  84. """
  85. This method sends bytes to the client. Returns False if an exception
  86. was raised during sending, otherwise True.
  87. """
  88. if log_msg:
  89. lschat.info("server:"+str(log_msg))
  90. else:
  91. lschat.info("Server:"+str(data))
  92. try:
  93. await self.socket.send(data)
  94. return True
  95. except Exception as e:
  96. lserver.error(e, exc_info=True)
  97. return False
  98. class ConnHandler(object):
  99. """
  100. More advanced connection handler than ConnectionHandlerBase. For
  101. instance, sends() takes a string and encodes it, recv() decodes
  102. the client's and returns a string and welcome_client is called after
  103. the ConnHandler is initialized (Not after the inheriting class is
  104. initialized though!)
  105. """
  106. def __init__(self, socket, addr, server):
  107. super(ConnHandler, self).__init__(socket,addr,server)
  108. async def disconnect(self):
  109. """
  110. disconenct() explicitely disconnects the client, performes a proper
  111. the shutdow on the socket and closes it.
  112. """
  113. try:
  114. await self.send("")
  115. except:
  116. lserver.debug("error during disconenct")
  117. try:
  118. await self.socket.shutdown(0)
  119. except:
  120. lserver.debug("error during socket shutdown")
  121. try:
  122. await self.socket.close()
  123. except:
  124. lserver.debug("error closing socket")
  125. async def handle(self, data):
  126. return
  127. async def on_welcome(self):
  128. """
  129. This method can be used to send a welcome message to the client.
  130. """
  131. self.send("Welcome client, this is the server sending!")
  132. async def recv(self,block_size=None):
  133. """
  134. This method waits for the client to send something, decodes it and
  135. returns a string.
  136. """
  137. if block_size == None:
  138. block_size = self.block_size
  139. data_received = await self.recv(block_size=block_size)
  140. data_decoded = data_received.decode("utf-8")
  141. return data_decoded
  142. async def send(self, data, log_msg=False):
  143. """
  144. This method takes a string, encodes it and sends it to the client.
  145. Returns False if an exception was raised during sending, otherwise True.
  146. """
  147. if log_msg:
  148. lschat.info("server:"+log_msg)
  149. else:
  150. lschat.info("Server:"+data)
  151. data_encoded = bytes(data, "utf-8")
  152. send_status = await self.send(data_encoded)
  153. return send_status
  154. class ConnHandlerEcho(ConnHandler):
  155. """
  156. A Conn handler which sends everything it receives to every other client
  157. connected to the server
  158. """
  159. def __init__(self, socket, addr, server):
  160. super(ConnHandlerEcho, self).__init__(socket, addr, server)
  161. def handle(self, data):
  162. for h in self.server.connection_handler:
  163. if not h is self:
  164. h.send(data)
  165. class Server(object):
  166. """
  167. Server opens either an unix or an inet connection. For every new client
  168. a new ClientHandler object is created.
  169. _string_ **host** and _int_ **port** are the filename, hostname or ip
  170. address and the port respectively on which the connection will be opened.
  171. If you make an AF_UNIX socket, port is ignored so simply pass None.
  172. _object_ **handler_class** is the class (not an object of the class) used
  173. for making connection handlers.
  174. _dict_ **handler_kwargs** is a dict which will be passed as keyword
  175. argumetns to the __init__ function of handler_class when creating a new
  176. connection handler. Default is an emtpy dict.
  177. _string_ **af_family** specifies the AF_FAMILY socket type, valid options
  178. are: "AF_INET" for a inet socket and "AF_UNIX" for a unix (file) socket.
  179. Default is "AF_INET".
  180. _bool_ **log_ip** specifies wether the ip address of the server/client is logged.
  181. Default is False.
  182. _int_ **max_allowed_clients** specifies the maximum amount of clients
  183. connected to the server at once. Default is 5 (for now. this will change
  184. in the future).
  185. """
  186. # set to true when the server shuts down, for instance after a
  187. # fatal exception
  188. exit_event = False
  189. def __init__(self,
  190. host,
  191. port,
  192. handler_class,
  193. handler_kwargs={},
  194. af_family="AF_INET",
  195. log_ip=False,
  196. max_allowed_clients=5,
  197. ):
  198. super(Server, self).__init__()
  199. self.host = host
  200. self.port = port
  201. self.handler_class = handler_class
  202. self.handler_kwargs = handler_kwargs
  203. self.af_family = af_family
  204. self.log_ip = log_ip
  205. self.max_allowed_clients = max_allowed_clients
  206. # don't make the socket yet, we don't need right now. will be created
  207. # when the start method is called
  208. self.socket = None
  209. # create a task group for handlers, so we can easily cancel/terminate
  210. # them all at once
  211. self.handle_tasks = curio.TaskGroup(name="tg_handle_clients")
  212. # list of all active connection handlers
  213. self.connection_handler = []
  214. # register our cleanup method to be executed when the program exits.
  215. # the cleanup function unregisters itself, so it won't get executed twice when the user called it befor the program exites
  216. atexit.register(self.shutdown)
  217. def make_socket(self):
  218. """
  219. factory method for sockets.
  220. this method makes a normal socket and wraps it in a curi.io.Socket wrapper
  221. """
  222. lserver.debug("making a {} socket".format(self.af_family))
  223. if self.af_family == "AF_INET":
  224. s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  225. elif self.af_family == "AF_UNIX":
  226. s = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
  227. else:
  228. raise ValueError(
  229. "AF_FAMILY '{}' not supported!".format(
  230. self.af_family
  231. )
  232. )
  233. s = curio.io.Socket(s)
  234. return s
  235. def make_handler(self, conn, addr):
  236. """
  237. factory method for handlers.
  238. this method creates a handler object from self.handler_class and self.handler_kwargs
  239. """
  240. return self.handler_class(conn, addr, self, **self.handler_kwargs)
  241. def setup(self):
  242. """
  243. creates a scoket, opens the connection and starts listening for
  244. clients. this method does not block, it returns after starting to
  245. listen.
  246. """
  247. lserver.info("setting up server")
  248. self.socket = self.make_socket()
  249. if self.af_family == "AF_INET":
  250. self.socket.bind((self.host, self.port))
  251. elif self.af_family == "AF_UNIX":
  252. if os.path.exists(self.host):
  253. lserver.debug("file already exists")
  254. lserver.debug("attempting to remove it")
  255. os.remove(self.host)
  256. self.socket.bind(self.host)
  257. self.socket.listen(self.max_allowed_clients)
  258. def shutdown(self):
  259. """
  260. This method properly shuts down the sockets and closes them.
  261. it unregisters itself from atexit, so it doesn't get executed twice
  262. when it was manually called before to program exits.
  263. """
  264. def error_handler(func,*args,log_text="error",async_=False,**kwargs):
  265. try:
  266. if async_:
  267. coro = func(*args,**kwargs)
  268. lserver.debug("{} {}".format(func,coro))
  269. else:
  270. func(*args,**kwargs)
  271. except Exception as exc:
  272. lserver.debug("error occured during "+log_text,exc_info=exc)
  273. atexit.unregister(self.shutdown)
  274. lserver.info("shutting down server")
  275. error_handler(
  276. self.handle_tasks.cancel_remaining,log_text="handler cancel",async_=True)
  277. # check if there is actually a socket. if the shutdown method is
  278. # executed before the start method, there is no socket.
  279. if self.socket:
  280. error_handler(self.socket.shutdown,log_text="socket shutdown")
  281. error_handler(self.socket.close,log_text="socket close")
  282. def start(self):
  283. """
  284. this method starts the server. it is blocking.
  285. """
  286. self.setup()
  287. curio.run(self.run)
  288. async def run(self):
  289. """
  290. this method is the main loop of the Server. it waits for new client
  291. connections and creates a handle task for each of them. it does not
  292. receive or send anything.
  293. """
  294. lserver.debug("entering main loop")
  295. while ( not self.exit_event ):
  296. lserver.debug("waiting for client to connect")
  297. # wait for a client to connect
  298. conn,addr = await self.socket.accept()
  299. if self.log_ip:
  300. lserver.info(
  301. "new client connection, {}:{}!".format(*addr))
  302. else:
  303. lserver.info("a new client connected, let's handle it")
  304. handler = self.make_handler(conn, addr)
  305. # self.register_conn(conn, addr)
  306. # self.register_handler(handler, conn)
  307. await self.handle_tasks.spawn(self.handle_client(conn,handler))
  308. async def handle_client(self,socket,handler):
  309. """
  310. This method waits for the client to send something and calls the
  311. ClientHandler's handle method. there is a handle_client method running for each client connected.
  312. """
  313. if hasattr(handler,"on_welcome"):
  314. await handler.on_welcome()
  315. while True:
  316. try:
  317. if self.log_ip:
  318. lserver.debug("waiting for {} to send something"
  319. .format(socket.getsockname()))
  320. else:
  321. lserver.debug("waiting for the client to send something")
  322. # wait for the client to send something
  323. data = await handler.recv()
  324. # if there is no data the client disconnected. this is a
  325. # tcp protocoll specification.
  326. if not data:
  327. if self.log_ip:
  328. lserver.info("the connection to {} was closed"
  329. .format(socket.getsockname()))
  330. else:
  331. lserver.info("the connection to the client was closed")
  332. # self.unregister_handler(handler, socket)
  333. # self.unregister_conn(socket)
  334. await handler.close()
  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. #