async_socket.py (2013B)
1 #
2 # Copyright (c) 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 #
18 # Simple socket example.
19 #
20 # The handler will asynchronously connect to the kore app itself and
21 # send an GET request to /socket-test and read the response.
22
23 import kore
24 import socket
25
26 @kore.route("/socket", methods=["get"])
27 async def async_socket(req):
28 # Create the socket using Pythons built-in socket class.
29 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
30
31 # Set it to nonblocking.
32 sock.setblocking(False)
33
34 # Create a kore.socket with kore.socket_wrap().
35 conn = kore.socket_wrap(sock)
36
37 # Asynchronously connect to 127.0.0.1 port 8888
38 await conn.connect("127.0.0.1", 8888)
39 kore.log(kore.LOG_INFO, "connected!")
40
41 # Now send the GET request
42 msg = "GET /socket-test HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"
43 await conn.send(msg.encode())
44 kore.log(kore.LOG_INFO, "request sent!")
45
46 # Read the response.
47 data = await conn.recv(8192)
48 kore.log(kore.LOG_INFO, "got response!")
49
50 # Respond with the response from /socket-test.
51 req.response(200, data)
52
53 conn.close()
54
55 @kore.route("/socket-test", methods=["get"])
56 async def socket_test(req):
57 # Delay response a bit, just cause we can.
58 await kore.suspend(5000)
59 req.response(200, b'response from /socket-test')