summaryrefslogtreecommitdiff
path: root/pgm4/tttmsg.c
blob: d5ffb5563c05a74488e3b158d6e2584b1ffbd0e7 (plain) (blame)
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
/* tttmsg.c
 *
 * Adam Carpenter - 2017
 */


#include "ttt.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int sendMessage(int connSock, char *message) {
    int left, num, put;
    left = MESSAGE_BUFF;
    put = 0;

    while (left > 0) {

        if ((num = write(connSock, message + put, left)) < 0) {
            // fprintf(stderr, "ttt/TTT: couldn't send message!\n");
            perror("ttt/TTT: couldn't send message because ");
            exit(1);
        }
        else if (num == 0) {
            return -1;
        }
        else {
            left -= num;
        }

        put += num;
    }

    return 0;
}

int getMessage(int connSock, char *message) {
    char ch;
    int i = 0;
    int num;

    for(i = 0; i < MESSAGE_BUFF; i++) {

        if ((num = read(connSock, &ch, 1)) < 0) {
            fprintf(stderr, "ttt/TTT: couldn't receive message!\n");
        }
        else if (num == 0) {
            return -1;
        }

        message[i] = ch;
    }

    return 0;
}