import asyncio
import threading
HOST = '127.0.0.1'
PORT = 9000
CLIENTS = []
async def echo_server(reader, writer):
while True:
data = await reader.read(100) # Max number of bytes to read
if not data:
break
writer.write(data)
await writer.drain() # Flow control, see later
writer.close()
async def startServer(host, port):
server = await asyncio.start_server(echo_server, host, port)
print(f"Server Started at {HOST} on {PORT}")
await server.serve_forever()
def setLoopEventForServerStart():
startServerLoop = asyncio.new_event_loop()
asyncio.set_event_loop(startServerLoop)
asyncio.run(startServer(HOST, PORT))
async def createClient():
client = await asyncio.open_connection(HOST, PORT)
if client:
CLIENTS.append(client)
print(f"Client appended {client}")
return client
def joinClient():
asyncio.run(joinClient())
async def sendMessageToServer(socket, message="hello World"):
reader, writer = socket
writer.write(message)
writer.drain()
startServerThread = threading.Thread(target=setLoopEventForServerStart)
startServerThread.start()
asyncio.run(createClient())
asyncio.run(createClient())
Error
Server Started at 127.0.0.1 on 9000
Traceback (most recent call last):
File "/home/needjobcoder/devlopment/python/_socketProgramming/asyncioTest.py", line 47, in <module>
asyncio.run(createClient())
File "/usr/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
return future.result()
File "/home/needjobcoder/devlopment/python/_socketProgramming/asyncioTest.py", line 29, in createClient
client = await asyncio.open_connection(HOST, PORT)
File "/usr/lib/python3.10/asyncio/streams.py", line 48, in open_connection
transport, _ = await loop.create_connection(
File "/usr/lib/python3.10/asyncio/base_events.py", line 1076, in create_connection
raise exceptions[0]
File "/usr/lib/python3.10/asyncio/base_events.py", line 1060, in create_connection
sock = await self._connect_sock(
File "/usr/lib/python3.10/asyncio/base_events.py", line 969, in _connect_sock
await self.sock_connect(sock, address)
File "/usr/lib/python3.10/asyncio/selector_events.py", line 501, in sock_connect
return await fut
File "/usr/lib/python3.10/asyncio/selector_events.py", line 541, in _sock_connect_cb
raise OSError(err, f'Connect call failed {address}')
ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 9000)