Inter-process communication (IPC) enables separate processes on the same machine to talk to each other. While web sockets and HTTP provide networking communication, sometimes processes just need to communicate locally in an efficient manner.
This is where Unix domain sockets (UDS) come in handy. The Python aiohttp library supports UDS as an alternative transport for its client and server implementations.
Why Use Unix Sockets?
Compared to localhost networking, UDS provide:
This makes UDS great for inter-process communication within the same machine.
aiohttp Unix Domain Socket Example
Here is a simple aiohttp server that will handle requests on a UDS instead of a network port:
import aiohttp
import asyncio
async def handle(request):
name = request.match_info.get('name', "Anonymous")
text = "Hello " + name
return aiohttp.web.Response(text=text)
app = aiohttp.web.Application()
app.add_routes([aiohttp.web.get('/', handle)])
async def start_unix_server():
await aiohttp.web.run_app(app, path='/tmp/myapp.sock')
loop = asyncio.get_event_loop()
loop.run_until_complete(start_unix_server())
loop.run_forever()
To access this server from other processes, simply point your aiohttp client to the socket file path instead of a host/port URL:
async with aiohttp.ClientSession() as session:
async with session.get('http+unix://%2Ftmp%2Fmyapp.sock') as resp:
print(await resp.text())
The key things to note are:
This allows quick and efficient IPC without the overhead of networking!