aboutsummaryrefslogtreecommitdiff
path: root/send.c
blob: def9e0ba55bd9e9278890a352e02ac31002428d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// minimal client implementation

#include <arpa/inet.h>
#include <assert.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "arena.h"
#include "common.h"

int main(int argc, char **argv)
{
    if (argc < 3) {
        fprintf(stderr, "usage: send <author> <msg>\n");
        return 1;
    }

    u32 err, serverfd, nsend;

    serverfd = socket(AF_INET, SOCK_STREAM, 0);
    assert(serverfd != -1);

    const struct sockaddr_in address = {
        AF_INET,
        htons(PORT),
        {0},
    };
    err = connect(serverfd, (struct sockaddr *)&address, sizeof(address));
    assert(err == 0);

    u32 author_len = strlen(argv[1]); // add 1 for null terminator
    assert(author_len + 1 <= AUTHOR_LEN);

    // convert text to wide string
    u32 text_len = strlen(argv[2]) + 1;
    wchar_t text_wide[text_len];
    u32 size = mbstowcs(text_wide, argv[2], text_len - 1);
    assert(size == text_len - 1);
    // null terminate
    text_wide[text_len - 1] = 0;

    Arena *bufArena = ArenaAlloc();
    u8 *buf = ArenaPush(bufArena, (text_len - 1) * sizeof(*text_wide));
    Message *mbuf = (Message *)buf;

    memcpy(mbuf->author, argv[1], author_len);
    message_timestamp(mbuf->timestamp);
    mbuf->text_len = text_len;
    memcpy(&mbuf->text, text_wide, mbuf->text_len * sizeof(wchar_t));

    nsend = send(serverfd, buf, MESSAGELENP(mbuf), 0);

    assert(nsend >= 0);

    printf("text_len: %d\n", text_len);
    fprintf(stdout, "Sent %d bytes.\n", nsend);

    ArenaRelease(bufArena);

    return 0;
}