I am trying to create a GUI chat app that uses async tcp as communication type and PyQT for GUI. I want to be able to send and receive messages both way (server2client, client2sever) but i couldn’t figure out how to send messages from server to client. I want to enter a messages as input and click “SEND” button.
self.connectionButton.pressed.connect(self.connection)
self.sendButton.pressed.connect(lambda: self.send_message_to_event_loop(self.lineEdit.text(), self.type1.currentText()))
def connection(self):
self.conType = self.type1.currentText()
if self.conType == "TCP Server":
self.send_message_to_event_loop("Server started", "TCP Server")
elif self.conType == "TCP Client":
print("Client")
self.send_message_to_event_loop("Client started", "TCP Client")
def send_message_to_event_loop(self, message: str, type_con) -> None:
"""Send the `asyncio` event loop's queue a message by using the coroutine
`put` and sending it to run on the `asyncio` event loop, putting the message
on the queue inside the event loop. This must be done because `asyncio.Queue`
is not threadsafe.
"""
asyncio.run_coroutine_threadsafe(
coro=self._async_queue.put((type_con, message)),
loop=self._asyncio_event_loop,
)
global_writer = None
async def handle_client(
reader: asyncio.StreamReader, writer: asyncio.StreamWriter
) -> None:
global global_writer
global_writer = writer
while True:
try:
data = await reader.read(100)
if not data:
break
message = data.decode().strip()
print(f"Received '{message}'")
global_writer.write("hello???".encode())
await writer.drain()
global_writer.close()
await global_writer.wait_closed()
except Exception as e:
print(f"Error: {e}")
break