|
1 /* |
|
2 * Sockets for TCP networking. |
|
3 * |
|
4 * This layer offers some functionality over what SDL_net offers directly: listening |
|
5 * sockets (called acceptors here) can be bound to port 0, which will make them listen |
|
6 * on a random unused port, if one can be found. To support this feature, you can also |
|
7 * query the local port that an acceptor is listening on. |
|
8 * |
|
9 * Further, we support nonblocking reads and writes here. The writes are buffered (TODO), |
|
10 * so that all data will be accepted, and you can configure a maximum buffer size |
|
11 * where the connection will be terminated. |
|
12 * |
|
13 * In order to ensure buffered data is actually sent out, you should regularly call |
|
14 * the tick function on your sockets. |
|
15 */ |
|
16 |
|
17 #ifndef SOCKET_H_ |
|
18 #define SOCKET_H_ |
|
19 |
|
20 #include <stdbool.h> |
|
21 #include <stdint.h> |
|
22 |
|
23 struct _flib_tcpsocket; |
|
24 typedef struct _flib_tcpsocket *flib_tcpsocket; |
|
25 |
|
26 struct _flib_acceptor; |
|
27 typedef struct _flib_acceptor *flib_acceptor; |
|
28 |
|
29 /** |
|
30 * Create a new acceptor which will listen for incoming TCP connections |
|
31 * on the given port. If port is 0, this will listen on a random |
|
32 * unused port which can then be queried with flib_acceptor_listenport. |
|
33 * |
|
34 * Can return NULL on error. |
|
35 */ |
|
36 flib_acceptor flib_acceptor_create(uint16_t port); |
|
37 |
|
38 /** |
|
39 * Return the port on which the acceptor is listening. |
|
40 */ |
|
41 uint16_t flib_acceptor_listenport(flib_acceptor acceptor); |
|
42 |
|
43 /** |
|
44 * Close the acceptor, free its memory and set it to NULL. |
|
45 * If the acceptor is already NULL, nothing happens. |
|
46 */ |
|
47 void flib_acceptor_close(flib_acceptor *acceptorptr); |
|
48 |
|
49 /** |
|
50 * Try to accept a connection from an acceptor (listening socket). |
|
51 * if localOnly is true, this will only accept connections which came from 127.0.0.1 |
|
52 * Returns NULL if nothing can be accepted. |
|
53 */ |
|
54 flib_tcpsocket flib_socket_accept(flib_acceptor acceptor, bool localOnly); |
|
55 |
|
56 /** |
|
57 * Close the socket, free its memory and set it to NULL. |
|
58 * If the socket is already NULL, nothing happens. |
|
59 */ |
|
60 void flib_socket_close(flib_tcpsocket *socket); |
|
61 |
|
62 /** |
|
63 * Attempt to receive up to maxlen bytes from the socket, but does not |
|
64 * block if nothing is available. |
|
65 * Returns the ammount of data received, 0 if there was nothing to receive, |
|
66 * or a negative number if the connection was closed or an error occurred. |
|
67 */ |
|
68 int flib_socket_nbrecv(flib_tcpsocket sock, void *data, int maxlen); |
|
69 |
|
70 int flib_socket_send(flib_tcpsocket sock, void *data, int len); |
|
71 |
|
72 #endif /* SOCKET_H_ */ |