Created
July 10, 2017 14:12
-
-
Save beltran/eb47ad90839e43bbde46dd2468b8b561 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncore, socket | |
from threading import Thread, Event | |
_dispatcher_map = {} | |
class Client(asyncore.dispatcher): | |
def __init__(self, host, port, message): | |
self._event = Event() | |
self.message = message | |
addresses = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM) | |
sockerr = None | |
for (af, socktype, proto, canonname, sockaddr) in addresses: | |
try: | |
self._socket = socket.socket(af, socktype, proto) | |
self._socket.settimeout(None) | |
self._socket.connect(sockaddr) | |
self._socket.settimeout(None) | |
sockerr = None | |
break | |
except socket.error as err: | |
if self._socket: | |
self._socket.close() | |
self._socket = None | |
sockerr = err | |
if sockerr: | |
raise Exception("Socker Error") | |
self._writable = True | |
self._readable = False | |
asyncore.dispatcher.__init__(self, self._socket, _dispatcher_map) | |
self.send(self.message) | |
self._event.wait() | |
def handle_close(self): | |
print("\n\n\nClosed by server, this shouldn't happen\n\n\n") | |
self.close() | |
def handle_read(self): | |
print('Received', self.recv(1024)) | |
self._event.set() | |
def handle_write(self): | |
self.send(self.message) | |
self._readable = True | |
self._writable = False | |
def readable(self): | |
return self._readable | |
# If this is set to true, the connection will be closed by the server | |
# otherwise it won't | |
use_poll = True | |
def _run_loop(): | |
while 1: | |
asyncore.loop(timeout=0.1, use_poll=use_poll, count=1, map = _dispatcher_map) | |
_thread = Thread(target=_run_loop, name="cassandra_driver_event_loop") | |
_thread.daemon = True | |
_thread.start() | |
for _ in range(1000): | |
c = Client('127.0.0.1', 5007, b'Hello, world') | |
c.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment