Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Async socket server and ports
Hi guys, first time posting on the Python forums

I am wondering how do asynchronous socket servers go about maintaining so many clients, specifically, how can the server have more than one client in a connected TCP stream if it is on a single port, or is there some automagical stuff happening to assign different ports behind the scenes?

for example in the doceumentation at
the server is serving on port 8888, however this expects multiple clients to have connections.

import asyncio

async def handle_echo(reader, writer):
    data = await
    message = data.decode()
    addr = writer.get_extra_info('peername')

    print(f"Received {message!r} from {addr!r}")

    print(f"Send: {message!r}")
    await writer.drain()

    print("Close the connection")

async def main():
    server = await asyncio.start_server(
        handle_echo, '', 8888)

    addr = server.sockets[0].getsockname()
    print(f'Serving on {addr}')

    async with server:
        await server.serve_forever()
With a trick the developers made asynchronous code looking like synchronous code.
They use generators with the send function, which allows to delegate everything.

It's a combination of:
  • DefaultSelector, which uses select, epoll and other os related selectors for sockets
  • Generators (await was before yield from, async was previously a normal generator with a yield statement used with send from outside)
  • EventLoop, which is asyncio.run_forever()

If you want to dig deeper in asyncio, you should watch some talks on YouTube.
Some of them are explaining it very deep.
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die:
All humans together. We don't need politicians!

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Question concerning function of a a socket pkm 4 1,070 Jun-04-2019, 07:48 AM
Last Post: DeaD_EyE
  socket.gaierror: [Errno -2] Name or service not known seokangwoo99 5 374 May-25-2019, 02:36 PM
Last Post: DeaD_EyE
  socket programming ConnectionRefusedError error srm 3 270 May-16-2019, 08:07 PM
Last Post: LavaCreeperKing
  Socket reading script Will86 4 323 Apr-17-2019, 06:57 AM
Last Post: Will86
  Server and Network (socket) [WinError 10053] SheeppOSU 2 362 Apr-13-2019, 09:23 PM
Last Post: SheeppOSU
  Multi connection socket server help! MuntyScruntfundle 0 274 Feb-19-2019, 12:03 PM
Last Post: MuntyScruntfundle
  socket programming (browser) kunz 8 810 Dec-18-2018, 10:13 AM
Last Post: siripriya
  Udp socket rocks88 3 593 Dec-02-2018, 01:26 AM
Last Post: Larz60+
  Multiple network socket servers? MuntyScruntfundle 1 468 Nov-13-2018, 03:46 PM
Last Post: wavic
  For Xilinx EthernetLite LWIP:Need help in Python SOCKET Coding Saras 1 602 Oct-01-2018, 05:16 AM
Last Post: Saras

Forum Jump:

Users browsing this thread: 1 Guest(s)