@@ -5,25 +5,58 @@ const zanzara = @import("src/zanzara.zig");
5
5
const DefaultClient = zanzara .mqtt4 .DefaultClient ;
6
6
const Subscribe = zanzara .mqtt4 .packet .Subscribe ;
7
7
8
+ const TcpConnectToAddressError = std .posix .SocketError || std .posix .ConnectError ;
9
+
10
+ fn tcpConnectToAddressNonBlock (address : net.Address ) TcpConnectToAddressError ! net.Stream {
11
+ const sock_flags = std .posix .SOCK .STREAM | std .posix .SOCK .NONBLOCK ;
12
+ const sockfd = try std .posix .socket (address .any .family , sock_flags , std .posix .IPPROTO .TCP );
13
+ errdefer net .Stream .close (.{ .handle = sockfd });
14
+
15
+ std .posix .connect (sockfd , & address .any , address .getOsSockLen ()) catch | err | {
16
+ switch (err ) {
17
+ error .WouldBlock = > std .time .sleep (1 * std .time .ns_per_s ), // Todo: handle this better
18
+ else = > return err ,
19
+ }
20
+ };
21
+
22
+ return net.Stream { .handle = sockfd };
23
+ }
24
+
25
+ fn tcpConnectToHostNonBlock (allocator : std.mem.Allocator , name : []const u8 , port : u16 ) net.TcpConnectToHostError ! net.Stream {
26
+ const list = try net .getAddressList (allocator , name , port );
27
+ defer list .deinit ();
28
+
29
+ if (list .addrs .len == 0 ) return error .UnknownHostName ;
30
+
31
+ for (list .addrs ) | addr | {
32
+ return tcpConnectToAddressNonBlock (addr ) catch | err | switch (err ) {
33
+ error .ConnectionRefused = > {
34
+ continue ;
35
+ },
36
+ else = > return err ,
37
+ };
38
+ }
39
+ return std .posix .ConnectError .ConnectionRefused ;
40
+ }
41
+
8
42
pub fn main () ! void {
9
43
var gpa = std .heap .GeneralPurposeAllocator (.{}){};
10
44
const allocator = gpa .allocator ();
11
45
12
- const stream = try net . tcpConnectToHost (allocator , "mqtt.eclipseprojects.io" , 1883 );
46
+ const stream = try tcpConnectToHostNonBlock (allocator , "mqtt.eclipseprojects.io" , 1883 );
13
47
const socket = stream .handle ;
14
48
const writer = stream .writer ();
15
49
16
- var mqtt_buf : [2048 ]u8 = undefined ;
50
+ var mqtt_buf : [32 * 2048 ]u8 = undefined ;
51
+ var client = try DefaultClient .init (mqtt_buf [0 .. 1024 * 32 ], mqtt_buf [1024 * 32 .. ]);
17
52
18
- var client = try DefaultClient .init (mqtt_buf [0.. 1024], mqtt_buf [1024.. ]);
19
53
// See ConnectOpts for additional options
20
54
try client .connect (.{ .client_id = "zanzara" });
21
55
22
- var read_buf : [2048 ]u8 = undefined ;
56
+ var read_buf : [32 * 2048 ]u8 = undefined ;
23
57
24
58
while (true ) {
25
- // We use os.MSG.DONTWAIT so the socket returns WouldBlock if no data is present
26
- const bytes = std .posix .recv (socket , & read_buf , std .posix .MSG .DONTWAIT ) catch | err |
59
+ const bytes = std .posix .recv (socket , & read_buf , 0 ) catch | err |
27
60
if (err == error .WouldBlock ) 0 else return err ;
28
61
var rest = read_buf [0.. bytes ];
29
62
while (true ) {
0 commit comments