Last active
December 17, 2015 15:59
-
-
Save aslpavel/5635559 to your computer and use it in GitHub Desktop.
Simple echo server (with pretzel framework)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Simple echo server | |
pretzel framework: https://github.com/aslpavel/pretzel | |
""" | |
from __future__ import print_function | |
import sys | |
import socket | |
from pretzel.app import app | |
from pretzel.monad import async | |
from pretzel.uniform import BrokenPipeError | |
from pretzel.stream import BufferedSocket | |
@async | |
def client_coro(sock, addr): | |
"""Client coroutine | |
""" | |
try: | |
print('[+clinet] fd:{} addr:{}'.format(sock.fileno(), addr)) | |
while True: | |
data = yield sock.read(1024) # receive data (throws an error if data is b'') | |
sock.write_schedule(data) # schedule data to be written | |
yield sock.flush() # flush buffered data | |
except BrokenPipeError: | |
pass | |
finally: | |
print('[-client] fd:{} addr:{}'.format(sock.fileno(), addr)) | |
sock.dispose() # close client socket (with context may be used) | |
@async | |
def server_coro(host, port): | |
"""Server coroutine | |
""" | |
with BufferedSocket(socket.socket()) as sock: # create async socket | |
sock.bind(('127.0.0.1', port)) # just bind | |
sock.listen(10) # just listen | |
print('[server] {}:{}'.format(host, port)) | |
while True: | |
client, addr = yield sock.accept() # asynchronously accept connection | |
client_coro(client, addr)() # start client coroutine (background) | |
@app | |
def main(): | |
if len(sys.argv) < 2: | |
sys.stderr.write('usage: {} <port>\n'.format(sys.argv[0])) | |
sys.exit(1) | |
yield server_coro('localhost', int(sys.argv[1])) # wait for server coroutine | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment