echo.py (2553B)
1 #
2 # Copyright (c) 2013-2018 Joris Vink <joris@coders.se>
3 #
4 # Permission to use, copy, modify, and distribute this software for any
5 # purpose with or without fee is hereby granted, provided that the above
6 # copyright notice and this permission notice appear in all copies.
7 #
8 # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 #
16
17 import kore
18 import socket
19
20 class EchoServer:
21 # Setup socket + wrap it inside of a kore socket so we can use it.
22 def __init__(self):
23 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
24 sock.setblocking(False)
25 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
26 sock.bind(("127.0.0.1", 6969))
27 sock.listen()
28
29 self.conn = kore.socket_wrap(sock)
30
31 # Wait for a new client to connect, then create a new task
32 # that calls handle_client with the ocnnected client as
33 # the argument.
34 async def run(self):
35 while True:
36 try:
37 client = await self.conn.accept()
38 kore.task_create(self.handle_client(client))
39 client = None
40 except Exception as e:
41 kore.fatal("exception %s" % e)
42
43 # Each client will run as this co-routine.
44 # In this case we pass a timeout of 1 second to the recv() call
45 # which will throw a TimeoutError exception in case the timeout
46 # is hit before data is read from the socket.
47 #
48 # This timeout argument is optional. If none is specified the call
49 # will wait until data becomes available.
50 async def handle_client(self, client):
51 while True:
52 try:
53 data = await client.recv(1024, 1000)
54 if data is None:
55 break
56 await client.send(data)
57 except TimeoutError as e:
58 print("timed out reading (%s)" % e)
59 except Exception as e:
60 print("client got exception %s" % e)
61 client.close()
62
63 # Setup the server object.
64 server = EchoServer()
65
66 # Create a task that will execute inside of Kore as a co-routine.
67 kore.task_create(server.run())