How do I create a public API for sending messages?
Let's say I have a connection that requires me to send a login message first, or maybe I wanna process some data and send a new message to server. How do I do that? Is this possible to do with asyncore?
Maybe the better question is how do I interact with this asyncore loop after starting it?
This is my attempt at doing something like this:
# package.coreio
import asyncore
from queue import Queue
class Client(asyncore.dispatcher):
"""This class represents a client to server connection."""
def __init__(self) -> None:
super().__init__()
self._host = ...
self._port = ...
self._messages = Queue()
self.create_socket()
self.connect((self._host, self._port))
def send_message(self, message: bytes) -> None:
"""A public API for sending messages to the server."""
self._messages.put(message)
def writable(self) -> None:
return not self._messages.empty()
def handle_write(self) -> None:
message = self._messages.get()
self.send(message)
print('Sending:', message)
def handle_read(self) -> None:
data = self.recv(4096)
print(data)
This is my attempt at using this interface:
import asyncore
import threading
import time
from .coreio import Client
login_message = ...
get_port = ...
client = Client()
client.send_message(login_message)
thread = threading.Thread(target=asyncore.loop)
thread.start()
time.sleep(2.5) # Do something for 2.5 seconds.
client.send_message(get_port) # Send another message.
Obviously it doesn't work.