Simplest way to write an async client server (like with that python library)

Dear Sirs,

I have a question about swift 5. With this release, is coming a library for the async programming?

I just want to write a very simple app like this in python (in python I have a third party library called AsyncIO, but maybe something like that could exist for swift):

Client:

TCP ECHO CLIENT:

import asyncio


async def tcp_echo_client(message, loop):
reader, writer = await asyncio.open_connection('127.0.0.1', 8888,
                                               loop=loop)

print('Send: %r' % message)
writer.write(message.encode())

data = await reader.read(100)
print('Received: %r' % data.decode())

print('Close the socket')
writer.close()


message = 'Hello World!'
loop = asyncio.get_event_loop()
loop.run_until_complete(tcp_echo_client(message, loop))
loop.close()

TCP ECHO SERVER:

import asyncio

async def handle_echo(reader, writer):
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print("Received %r from %r" % (message, addr))

print("Send: %r" % message)
writer.write(data)
await writer.drain()

print("Close the client socket")
writer.close()

loop = asyncio.get_event_loop()
coro = asyncio.start_server(handle_echo, '127.0.0.1', 8888, loop=loop)
server = loop.run_until_complete(coro)

# Serve requests until Ctrl+C is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
try:
 loop.run_forever()
except KeyboardInterrupt:
  pass

# Close the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()

There is a way to write something simple like that in swift 5?

This sounds like a good job for SwiftNIO. The default repository contains an example echo client and example echo server. There are a few more examples like HTTP/WebSocket servers in that repo. Larger examples can be found in swift-nio-examples.

SwiftNIO is also has its own category in the forums under Related Projects -> SwiftNIO where we are very happy to answer questions regarding SwiftNIO and the implementation of network servers/clients/protocols/... with SwiftNIO. The API docs can be found here.

3 Likes

Thanks a lot for the reply!

Terms of Service

Privacy Policy

Cookie Policy