Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from fiber import Fiber
2from fiber import current
3from fiber import suspend
5c"""
6static void on_send_complete(uv_udp_send_t *request_p, int status)
7{
8 Socket *socket_p = (Socket *)(request_p->data);
10 if (status == -1) {
11 fprintf(stderr, "Send error!\n");
12 }
14 resume(socket_p->_fiber);
15}
16"""
18class Socket:
19 c"""
20 uv_udp_t m_socket;
21 uv_udp_send_t m_send;
22 uv_buf_t m_buf;
23 """
24 _fiber: Fiber?
26 func __init__(self):
27 c"""
28 uv_udp_init(uv_default_loop(), &m_socket);
29 m_socket.data = this;
30 m_send.data = this;
31 """
33 self._fiber = None
35 func _wait_for_completion(self):
36 self._fiber = current()
37 suspend()
38 self._fiber = None
40 func bind(self, port: i64):
41 """Bind the socket to given local port. Used both when sending and
42 receiving packtes.
44 """
46 raise NotImplementedError()
48 func connect(self, host: string, port: i64):
49 """Connect the socket to given remote host and port. Sent packages are
50 sent to this address by default.
52 """
54 raise NotImplementedError()
56 func send(self, data: bytes):
57 raise NotImplementedError()
59 func send_to(self, data: bytes, host: string, port: i64):
60 """Send given data to given address.
62 """
64 host_utf8 = host.to_utf8()
65 host_utf8 += 0
67 c"""
68 struct sockaddr_in addr;
69 uv_ip4_addr((const char *)host_utf8.m_bytes->data(), port, &addr);
70 m_buf = uv_buf_init((char *)data.m_bytes->data(), data.m_bytes->size());
71 uv_udp_send(&m_send,
72 &m_socket,
73 &m_buf,
74 1,
75 (const struct sockaddr *)&addr,
76 on_send_complete);
77 """
79 self._wait_for_completion()
81 func receive(self) -> bytes:
82 raise NotImplementedError()
84 func receive_from(self) -> (bytes, string, i64):
85 raise NotImplementedError()