Multiagent in Python using Spade localhost configuration issue - python

I want to try Multi Agent programming in Python using SPADE, but i can't seem to make this simple example work. The error refers to the server, so how can i set up the agents to work in the localhost ?
here is my code :
class SenderAgent(Agent):
class InformBehav(OneShotBehaviour):
async def run(self):
print("InformBehav running")
msg = Message(to="receiveragent#127.0.0.1") # Instantiate the message
msg.set_metadata("performative", "inform") # Set the "inform" FIPA performative
msg.body = "Hello World" # Set the message content
await self.send(msg)
print("Message sent!")
# stop agent from behaviour
await self.agent.stop()
async def setup(self):
print("SenderAgent started")
b = self.InformBehav()
self.add_behaviour(b)
class ReceiverAgent(Agent):
class RecvBehav(OneShotBehaviour):
async def run(self):
print("RecvBehav running")
msg = await self.receive(timeout=10) # wait for a message for 10 seconds
if msg:
print("Message received with content: {}".format(msg.body))
else:
print("Did not received any message after 10 seconds")
# stop agent from behaviour
await self.agent.stop()
async def setup(self):
print("ReceiverAgent started")
b = self.RecvBehav()
template = Template()
template.set_metadata("performative", "inform")
self.add_behaviour(b, template)
if __name__ == "__main__":
receiveragent = ReceiverAgent("receiveragent#127.0.0.1", '1234')
future = receiveragent.start()
future.result() # wait for receiver agent to be prepared.
senderagent = SenderAgent("senderagent#127.0.0.1", '1234')
senderagent.start()
while receiveragent.is_alive():
try:
time.sleep(1)
except KeyboardInterrupt:
senderagent.stop()
receiveragent.stop()
break
print("Agents finished")
as i'm getting the following errors :
connection failed: [Errno 10061] Connect call failed ('127.0.0.1', 5222)
Traceback (most recent call last):
File "C:/Users/Administrateur/PycharmProjects/spade/test.py", line 53, in <module>
future.result() # wait for receiver agent to be prepared.
File "C:\Users\Administrateur\AppData\Local\Programs\Python\Python37\lib\concurrent\futures\_base.py", line 435, in result
return self.__get_result()
File "C:\Users\Administrateur\AppData\Local\Programs\Python\Python37\lib\concurrent\futures\_base.py", line 384, in __get_result
raise self._exception
File "C:\Users\Administrateur\AppData\Local\Programs\Python\Python37\lib\site-packages\spade\agent.py", line 100, in _async_start
await self._async_register()
File "C:\Users\Administrateur\AppData\Local\Programs\Python\Python37\lib\site-packages\spade\agent.py", line 142, in _async_register
_, stream, features = await aioxmpp.node.connect_xmlstream(self.jid, metadata, loop=self.loop)
File "C:\Users\Administrateur\AppData\Local\Programs\Python\Python37\lib\site-packages\aioxmpp\node.py", line 415, in connect_xmlstream
exceptions
aioxmpp.errors.MultiOSError: failed to connect to XMPP domain '127.0.0.1': multiple errors: [Errno 10061] Connect call failed ('127.0.0.1', 5222)

Related

Unable to Perform Graceful Shutdown of Asyncio App after a KeyboardInterrupt

I am having trouble letting my asyncio app shutdown gracefully when the user creates a KeyboardInterrupt by pressing Ctrl+C.
Why is it still not working properly despite using try... except KeyboardInterrupt? It still shows a traceback and something about a Unclosed AIOKafkaProducer.
import asyncio
from aiokafka import AIOKafkaProducer
class Foo:
def __init__(self):
self.producer = None
async def start(self):
self.producer = AIOKafkaProducer(bootstrap_servers="localhost:29092")
await self.producer.start()
self.loop_task = asyncio.create_task(self.loop())
await asyncio.gather(*[self.loop_task])
async def stop(self):
self.loop_task.cancel()
await self.producer.stop()
async def loop(self):
while True:
await asyncio.sleep(5)
async def main():
foo = Foo()
try:
await foo.start()
except KeyboardInterrupt:
print(
"Attempting graceful shutdown, press Ctrl+C+ again to exit...", flush=True
)
await foo.stop()
if __name__ == "__main__":
asyncio.run(main())
Error messages after pressing pressing Ctrl+C:
^CTraceback (most recent call last):
File "/home/x/test.py", line 37, in <module>
asyncio.run(main())
File "/opt/anaconda3/envs/testenv/lib/python3.9/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/opt/anaconda3/envs/testenv/lib/python3.9/asyncio/base_events.py", line 629, in run_until_complete
self.run_forever()
File "/opt/anaconda3/envs/testenv/lib/python3.9/asyncio/base_events.py", line 596, in run_forever
self._run_once()
File "/opt/anaconda3/envs/testenv/lib/python3.9/asyncio/base_events.py", line 1854, in _run_once
event_list = self._selector.select(timeout)
File "/opt/anaconda3/envs/testenv/lib/python3.9/selectors.py", line 469, in select
fd_event_list = self._selector.poll(timeout, max_ev)
KeyboardInterrupt
Unclosed AIOKafkaProducer
producer: <aiokafka.producer.producer.AIOKafkaProducer object at 0x7f643c0d0c40>
Adding try...except around main()
if __name__ == "__main__":
try:
asyncio.run(main())
except Exception as e:
print("Exception:", e)
This gave the same traceback

Why does calling asyncio.sleep causes websocket connection to close?

I am trying to build a websockets server where the client connects and sends a request of some kind, and then the server adds that request to a queue and returns something back when finished.
to simulate the process of queueing and waiting for tasks to finish, I called asyncio.sleep whenever the process is supposed to be called.
however, whenever I do that I get the following error from the client-side:
Traceback (most recent call last):
File "D:/Python/server/client1.py", line 10, in <module>
asyncio.get_event_loop().run_until_complete(message())
File "C:\ProgramData\Anaconda3\envs\server\lib\asyncio\base_events.py", line 587, in run_until_complete
return future.result()
File "D:/Python/server/client1.py", line 8, in message
print(await socket.recv())
File "C:\ProgramData\Anaconda3\envs\server\lib\site-packages\websockets\protocol.py", line 509, in recv
await self.ensure_open()
File "C:\ProgramData\Anaconda3\envs\server\lib\site-packages\websockets\protocol.py", line 812, in ensure_open
raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedOK: code = 1000 (OK), no reason
and this error from the server-side:
Task exception was never retrieved
future: <Task finished coro=<queue_dispatcher() done, defined at D:/RamNew2020/Python/server/asyncserver.py:39> exception=ConnectionClosedOK('code = 1000 (OK), no reason')>
Traceback (most recent call last):
File "D:/Python/server/asyncserver.py", line 45, in queue_dispatcher
await data_from_q.sendto_websocket("yay")
File "D:/Python/server/asyncserver.py", line 20, in sendto_websocket
await self.mywebsocket.send(message)
File "C:\ProgramData\Anaconda3\envs\server\lib\site-packages\websockets\protocol.py", line 555, in send
await self.ensure_open()
File "C:\ProgramData\Anaconda3\envs\server\lib\site-packages\websockets\protocol.py", line 803, in ensure_open
raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedOK: code = 1000 (OK), no reason
My scripts:
server.py:
import asyncio
import websockets
import datetime
import random
queue = asyncio.Queue()
async def rnd_sleep(t):
# sleep for T seconds on average
await asyncio.sleep(t * random.random() * 2)
#When a client sends a message the information is saved in a Request object,
#including the socket connection
class Request:
def __init__(self, mywebsocket, mydat):
self.mywebsocket = mywebsocket
self.mydat = mydat
self.start_time_of_request = datetime.datetime.now()
self.id = random.randint(0, 128)
async def sendto_websocket(self, message):
await self.mywebsocket.send(message)
def get_dat(self):
return self.mydat
def get_start_time(self):
return self.start_time_of_request
async def add_to_queue(websocket, path):
global queue
dat = await websocket.recv()
base64dat = Request(websocket, dat)
await queue.put(base64dat)
#problem in queue_dispatcher
async def queue_dispatcher(q):
while True:
data_from_q = await q.get()
print(data_from_q.id)
await asyncio.sleep(1) #The problem is here, whenever I remove it, it works
await data_from_q.sendto_websocket("yay")
q.task_done()
async def main():
global queue
asyncio.create_task(queue_dispatcher(queue))
pass
start_server = websockets.serve(add_to_queue, 'localhost', 5000)
asyncio.get_event_loop().run_until_complete(main())
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
client.py:
import asyncio
async def message():
async with websockets.connect("ws://localhost:5000")as socket:
msg = input("What do you want to send: ")
await socket.send(msg)
print(await socket.recv())
asyncio.get_event_loop().run_until_complete(message())
In addition, whenever I try to await any other async function, it works fine no matter how long.

Python Correct Way to Use asyncio streams to open a connection, send and receive multiple transmissions, then close connection gracefully

I am asking where either my though process or my code is incorrect relative to using asyncio client streams to send data and receive responses from a server. When I call the method that disconnects the client an exception is thrown. I am learning python asyncio and ran across exceptions during testing trying to close the client connection. I am trying to 1). Create a client connection to a server 2). leave the client connection open so that it can be used across multiple send/receive cycles 3). close the client connection gracefully when complete.
This is the class that contains the asyncio methods to create the stream writer.
class hl7_client_sender:
SB = b'\x1B'
EB = b'\x1C'
CR = b'\x0D'
def __init__(self,address,port,timeout=-1,retry=3.0):
self._resend=0
self._timeout= timeout
self._retry = retry
#self._reader, self._writer = await asyncio.open_connection(address,port)
self._address = address
self._port = port
self._writer = None
self._reader = None
async def connect(self):
self._reader, self._writer = await asyncio.open_connection(self._address,self._port)
async def disconnect(self):
await self._writer.wait_closed()
and this is the code in my driver where the exception occurs during the call to disconnect
#test send and respond
import asyncio
import string
import unicodedata
import simple_hl7_client
import time
##open a connectino sleep 5 seconds then close###
myclient = simple_hl7_client.hl7_client_sender('192.168.226.128',54321)
asyncio.run(myclient.connect())
time.sleep(3)
asyncio.run(myclient.disconnect())
The exception occurs during the call to asycnio.run(myclient.disconnect())
This is the exception:
Traceback (most recent call last):
File ".\test_simple_hl7_client.py", line 11, in <module>
asyncio.run(myclient.disconnect())
File "C:\Users\billg\AppData\Local\Programs\Python\Python37\lib\asyncio\runners.py", line 43, in run
return loop.run_until_complete(main)
File "C:\Users\billg\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 583, in run_until_complete
return future.result()
File "D:\data\FromOldPC\code\ASYNCIOTESTING\simple_hl7_client.py", line 23, in disconnect
self._writer.close()
File "C:\Users\billg\AppData\Local\Programs\Python\Python37\lib\asyncio\streams.py", line 317, in close
return self._transport.close()
File "C:\Users\billg\AppData\Local\Programs\Python\Python37\lib\asyncio\selector_events.py", line 663, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\billg\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 687, in call_soon
self._check_closed()
File "C:\Users\billg\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 479, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

Python-Asyncio TCP Server keep connecting to another remote TCP server

Is there any code snippet sample to achieve the following requirement,
python-asyncio TCP Server listen for TCP client and manage open connection simultaneously to another remote TCP server.
the tcp server code that I've tried so far, based on: http://asyncio.readthedocs.io/en/latest/tcp_echo.html1
HOST, PORT = '127.0.0.1', 8888
VHOST, VPORT = "localhost", 9999
vsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
vsock.connect((VHOST, VPORT))
async def send_message(message, vsock):
receive = None
try:
vsock.sendall(message)
received = vsock.recv(1024)
except:
print("Unexpected error:", sys.exc_info()[0])
raise
return received
async def handle_echo(reader, writer):
task = loop.create_task(send_message(data, vsock))
response = await task
writer.write(response)
await writer.drain()
writer.close()
loop = asyncio.get_event_loop()
coro = asyncio.start_server(handle_echo, HOST, PORT, loop=loop)
server = loop.run_until_complete(coro)
try:
loop.run_forever()
except KeyboardInterrupt:
pass
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
vsock.close()
It works on first request, but getting blank message in 2nd request, and getting error the next request
Unexpected error: <class 'BrokenPipeError'>
Task exception was never retrieved
future: <Task finished coro=<handle_echo() done, defined at socket_server.py:27> exception=BrokenPipeError(32, 'Broken pipe')>
Traceback (most recent call last):
File "/home/hery/.pyenv/versions/3.5.1/lib/python3.5/asyncio/tasks.py", line 241, in _step
result = coro.throw(exc)
File "socket_server.py", line 34, in handle_echo
response = await task
File "/home/hery/.pyenv/versions/3.5.1/lib/python3.5/asyncio/futures.py", line 358, in __iter__
yield self # This tells Task to wait for completion.
File "/home/hery/.pyenv/versions/3.5.1/lib/python3.5/asyncio/tasks.py", line 290, in _wakeup
future.result()
File "/home/hery/.pyenv/versions/3.5.1/lib/python3.5/asyncio/futures.py", line 274, in result
raise self._exception
File "/home/hery/.pyenv/versions/3.5.1/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "socket_server.py", line 18, in send_message
vsock.sendall(message)
BrokenPipeError: [Errno 32] Broken pipe

How to get gevent websockets working?

I am using geventwebsockets but can't even get the example app to work. The code below gives me the error:
Traceback (most recent call last): File
"/usr/local/lib/python2.7/dist-packages/gevent/pywsgi.py", line 884,
in handle_one_response
self.run_application() File "/usr/local/lib/python2.7/dist-packages/geventwebsocket/handler.py",
line 88, in run_application
return super(WebSocketHandler, self).run_application() File "/usr/local/lib/python2.7/dist-packages/gevent/pywsgi.py", line 870,
in run_application
self.result = self.application(self.environ, self.start_response) File
"/usr/local/lib/python2.7/dist-packages/geventwebsocket/resource.py",
line 90, in call
raise Exception("No apps defined") Exception: No apps defined
from geventwebsocket import WebSocketServer, WebSocketApplication, Resource
class EchoApplication(WebSocketApplication):
def on_open(self):
print "Connection opened"
def on_message(self, message):
self.ws.send(message)
def on_close(self, reason):
print reason
WebSocketServer(
('', 8000),
Resource({'/': EchoApplication})
).serve_forever()
I've been running around in circles. Can anyone help me out? Thanks so much.
Does it work for you
if you add the echo_app
def echo_app(environ, start_response):
websocket = environ.get("wsgi.websocket")
if websocket is None:
return http_handler(environ, start_response)
try:
while True:
message = websocket.receive()
websocket.send(message)
websocket.close()
except geventwebsocket.WebSocketError, ex:
print "{0}: {1}".format(ex.__class__.__name__, ex)
and
pass it like
print "Running %s from %s" % (agent, path)
WebSocketServer(("", 8000), echo_app, debug=False).serve_forever()
as shown in
https://bitbucket.org/noppo/gevent-websocket/src/0df192940acd288e8a8f6d2dd30329a3381c90f1/examples/echoserver.py

Categories

Resources