2
0

socket.zig 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. const std = @import("std");
  2. const net = std.net;
  3. const posix = std.posix;
  4. pub fn setReadTimeout(conn: posix.socket_t, seconds: u32) !void {
  5. const timeout = posix.timeval{
  6. .sec = @intCast(seconds),
  7. .usec = 0,
  8. };
  9. try posix.setsockopt(conn, posix.SOL.SOCKET, posix.SO.RCVTIMEO, &std.mem.toBytes(timeout));
  10. }
  11. pub fn setWriteTimeout(conn: posix.socket_t, seconds: u32) !void {
  12. const timeout = posix.timeval{
  13. .sec = @intCast(seconds),
  14. .usec = 0,
  15. };
  16. try posix.setsockopt(conn, posix.SOL.SOCKET, posix.SO.SNDTIMEO, &std.mem.toBytes(timeout));
  17. }
  18. pub fn init(port: u16) !posix.socket_t {
  19. const address = try std.net.Address.parseIp("0.0.0.0", port);
  20. const tpe: u32 = posix.SOCK.STREAM;
  21. const protocol = posix.IPPROTO.TCP;
  22. const listener = try posix.socket(address.any.family, tpe, protocol);
  23. try posix.setsockopt(listener, posix.SOL.SOCKET, posix.SO.REUSEADDR, &std.mem.toBytes(@as(c_int, 1)));
  24. try posix.setsockopt(listener, posix.SOL.SOCKET, posix.SO.RCVBUF, &std.mem.toBytes(@as(c_int, 1048576))); // 1MB receive buffer
  25. try posix.setsockopt(listener, posix.SOL.SOCKET, posix.SO.SNDBUF, &std.mem.toBytes(@as(c_int, 1048576))); // 1MB send buffer
  26. try posix.bind(listener, &address.any, address.getOsSockLen());
  27. try posix.listen(listener, 1024); // Increased backlog
  28. return listener;
  29. }
  30. pub fn readUntilCR(conn: posix.socket_t, buf: []u8) !usize {
  31. var total: usize = 0;
  32. while (total < buf.len) {
  33. const n = try posix.read(conn, buf[total..]);
  34. if (n == 0) {
  35. return if (total > 0) total else error.ConnectionClosed;
  36. }
  37. if (std.mem.indexOfScalar(u8, buf[total .. total + n], '\r')) |offset| {
  38. return total + offset;
  39. }
  40. total += n;
  41. }
  42. return total;
  43. }
  44. pub fn read(conn: posix.socket_t, buf: []u8) !usize {
  45. var pos: usize = 0;
  46. while (pos < buf.len) {
  47. const n = try posix.read(conn, buf[pos..]);
  48. if (n == 0) {
  49. return pos;
  50. }
  51. pos += n;
  52. }
  53. return pos;
  54. }
  55. pub fn write(conn: posix.socket_t, msg: []const u8) !void {
  56. const written = try posix.write(conn, msg);
  57. if (written != msg.len) {
  58. return error.PartialWrite;
  59. }
  60. }
  61. pub fn writev(conn: posix.socket_t, iovecs: []const posix.iovec_const) !void {
  62. var total: usize = 0;
  63. for (iovecs) |iov| {
  64. total += iov.len;
  65. }
  66. const written = try posix.writev(conn, iovecs);
  67. if (written != total) {
  68. return error.PartialWrite;
  69. }
  70. }