socket.zig 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. const std = @import("std");
  2. const net = std.net;
  3. const posix = std.posix;
  4. pub fn init(port: u16) !posix.socket_t {
  5. const address = try std.net.Address.parseIp("0.0.0.0", port);
  6. const tpe: u32 = posix.SOCK.STREAM;
  7. const protocol = posix.IPPROTO.TCP;
  8. const listener = try posix.socket(address.any.family, tpe, protocol);
  9. try posix.setsockopt(listener, posix.SOL.SOCKET, posix.SO.REUSEADDR, &std.mem.toBytes(@as(c_int, 1)));
  10. try posix.bind(listener, &address.any, address.getOsSockLen());
  11. try posix.listen(listener, 128);
  12. return listener;
  13. }
  14. pub fn readUntilCR(conn: posix.socket_t, buf: []u8) !usize {
  15. var total: usize = 0;
  16. while (total < buf.len) {
  17. const n = try posix.read(conn, buf[total..]);
  18. if (n == 0) {
  19. return if (total > 0) total else error.ConnectionClosed;
  20. }
  21. if (std.mem.indexOfScalar(u8, buf[total .. total + n], '\r')) |offset| {
  22. return total + offset;
  23. }
  24. total += n;
  25. }
  26. return total;
  27. }
  28. pub fn readUntilNewLine(conn: posix.socket_t, buf: []u8) !usize {
  29. var pos: usize = 0;
  30. while (pos < buf.len) {
  31. const n = try posix.read(conn, buf[pos .. pos + 1]);
  32. if (n == 0) {
  33. return pos;
  34. }
  35. if (buf[pos] == '\n') {
  36. return pos + 1;
  37. }
  38. pos += n;
  39. }
  40. return pos;
  41. }
  42. pub fn read(conn: posix.socket_t, buf: []u8) !usize {
  43. var pos: usize = 0;
  44. while (pos < buf.len) {
  45. const n = try posix.read(conn, buf[pos..]);
  46. if (n == 0) {
  47. return pos;
  48. }
  49. pos += n;
  50. }
  51. return pos;
  52. }
  53. pub fn write(conn: posix.socket_t, msg: []const u8) !void {
  54. const written = try posix.write(conn, msg);
  55. if (written != msg.len) {
  56. return error.PartialWrite;
  57. }
  58. }