aboutsummaryrefslogtreecommitdiff
path: root/src/graveyard/win32/win32_network_stream.cpp
blob: 11a180e791ff2a51461fa44f2411d013c1acfb38 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <platform/platform.h>
#include <windows.h>
#include <stdlib.h>

static b32 g_wsa_started;

struct PlatformNetworkStream {
    SOCKET socket;
};

PlatformNetworkStream *platform_network_stream_open_connection() {
    PlatformNetworkStream *stream = (PlatformNetworkStream*)malloc(sizeof(*stream));
    int err;

    // start wsa
    if (!g_wsa_started) {
        WSADATA wsa_data;
        WORD wsa_version = MAKEWORD(2, 2);
        err = WSAStartup(wsa_version, &wsa_data);
        if (err) {
            printf("WSAStartup error %d\n", err);
            return false;
        }
        g_wsa_started = true;
    }

    // open socket
    SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sock == INVALID_SOCKET) {
        printf("socket() wsa error: %d\n", WSAGetLastError());
        return false;
    }

    // connect
    struct sockaddr_in sa = {};
    sa.sin_family = AF_INET;
    sa.sin_port = htons(port);
    sa.sin_addr.s_addr = inet_addr(address);

    err = connect(sock, (SOCKADDR*)&sa, sizeof(sa));
    if (err) {
        printf("connect() wsa error: %d\n", WSAGetLastError());
        closesocket(sock);
        return false;
    }

    // make socket non-blocking
    u_long io_mode = 1;
    err = ioctlsocket(sock, FIONBIO, &io_mode);
    if (err) {
        printf("ioctlsocket() wsa error: %d\n", WSAGetLastError());
        closesocket(sock);
        return false;
    }

    m_Socket = sock;
    return true;
}

void platform_network_stream_close(PlatformNetworkStream *stream) {
    int err = closesocket(m_Socket);
    if (err) {
        printf("closesocket() wsa error: %d\n", WSAGetLastError());
    }
}

bool platform_network_stream_send(PlatformNetworkStream *stream, void *buff, i32 size) {
    int sent = send(m_Socket, (const char*)buff, size, 0);
    if (sent == SOCKET_ERROR) {
        int error_code = WSAGetLastError();
        printf("send() wsa error = %d\n", error_code);
        return false;
    }
    return true;
}

i64 platform_network_stream_recv(PlatformNetworkStream *stream, void *buff, i64 size) {
    int recvd = recv(m_Socket, (char*)buff, size, 0);
    if (recvd == SOCKET_ERROR) {
        int error_code = WSAGetLastError();
        if (error_code == WSAEWOULDBLOCK) {
            return 0;
        } else {
            printf("recv() wsa error: %d\n", error_code);
            return -1;
        }
    }
    return recvd;
}