Last active
December 8, 2024 15:01
-
-
Save tetsu-koba/ee182b60ca5f8d44f5c4657903d31593 to your computer and use it in GitHub Desktop.
UDP client library for Zig
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
UDP client library for Zig |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
const os = std.os; | |
const net = std.net; | |
pub fn udpConnectToAddress(address: net.Address) !net.Stream { | |
const sockfd = try os.socket(os.AF.INET, os.SOCK.DGRAM | os.SOCK.CLOEXEC, 0); | |
errdefer os.closeSocket(sockfd); | |
try os.connect(sockfd, &address.any, address.getOsSockLen()); | |
return net.Stream{ .handle = sockfd }; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
const udp = @import("udp.zig"); | |
const os = std.os; | |
const log = std.log; | |
const time = std.time; | |
const net = std.net; | |
const UDP_PAYLOADSIZE = 65507; | |
fn helloToServer(adr: []const u8, port: u16, verbose:bool) !void { | |
const a = try net.Address.resolveIp(adr, port); | |
var s = try udp.udpConnectToAddress(a); | |
defer s.close(); | |
if (verbose) { | |
log.info("{d}:Connected.", .{time.milliTimestamp()}); | |
} | |
const bytes_write = try s.write("Hello from client."); | |
if (verbose) { | |
log.info("{d}:bytes_write={d}", .{time.milliTimestamp(),bytes_write}); | |
} | |
var buf: [UDP_PAYLOADSIZE]u8 = .{}; | |
const bytes_read = try s.read(&buf); | |
if (verbose) { | |
log.info("{d}:Got message [{s}].", .{time.milliTimestamp(),buf[0..bytes_read]}); | |
} | |
} | |
pub fn main() !void { | |
// TODO: get parameters from command line options | |
const verbose = true; | |
const adr = "127.0.0.1"; | |
const port = 7200; | |
try helloToServer(adr, port, verbose); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment