summaryrefslogtreecommitdiffstats
path: root/libsysutils/src/SocketClient.cpp
blob: 6db62b3093b832b5c0b8e1ce9fdb1b29d5d179ba (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
#include <alloca.h>
#include <errno.h>
#include <sys/types.h>
#include <pthread.h>

#define LOG_TAG "SocketClient"
#include <cutils/log.h>

#include <sysutils/SocketClient.h>

SocketClient::SocketClient(int socket) {
    mSocket = socket;
    pthread_mutex_init(&mWriteMutex, NULL);
}

int SocketClient::sendMsg(char *msg) {
    LOGD("SocketClient::sendMsg(%s)", msg);
    if (mSocket < 0) {
        errno = EHOSTUNREACH;
        return -1;
    }

    pthread_mutex_lock(&mWriteMutex);
    if (write(mSocket, msg, strlen(msg) +1) < 0) {
        LOGW("Unable to send msg '%s' (%s)", msg, strerror(errno));
    }
    pthread_mutex_unlock(&mWriteMutex);
    return 0;
}

int SocketClient::sendMsg(char *msg, char *data) {
    char *buffer = (char *) alloca(strlen(msg) + strlen(data) + 1);
    if (!buffer) {
        errno = -ENOMEM;
        return -1;
    }
    strcpy(buffer, msg);
    strcat(buffer, data);
    return sendMsg(buffer);
}