def connect_with(protocol_class, host_port: tuple,
args: list, kwargs: dict):
""" Helper which creates a new connection and feeds the data stream into
a protocol handler class.
:rtype: tuple(protocol_class, gevent.socket)
:type protocol_class: class
:param protocol_class: A handler class which has handler functions like
on_connected, consume, and on_connection_lost
:param kwargs: Keyword args to pass to the handler class constructor
:param args: Args to pass to the handler class constructor
:param host_port: (host,port) tuple where to connect
"""
sock = socket.create_connection(address=host_port)
handler = protocol_class(*args, **kwargs)
handler.on_connected(sock, host_port)
print("Connection to %s established" % str(host_port))
try:
g = gevent.spawn(_handle_socket_read, handler, sock)
g.start()
except Exception as e:
print("\nException: %s" % e)
traceback.print_exc()
print()
return handler, sock
评论列表
文章目录