SocketClient.cpp revision d768066ef54270a0d3ccfccd50ae8238db5a2cdd
1#include <alloca.h> 2#include <errno.h> 3#include <sys/types.h> 4#include <pthread.h> 5#include <string.h> 6 7#define LOG_TAG "SocketClient" 8#include <cutils/log.h> 9 10#include <sysutils/SocketClient.h> 11 12SocketClient::SocketClient(int socket) { 13 mSocket = socket; 14 pthread_mutex_init(&mWriteMutex, NULL); 15} 16 17int SocketClient::sendMsg(int code, char *msg, bool addErrno) { 18 char *buf; 19 20 if (addErrno) { 21 buf = (char *) alloca(strlen(msg) + strlen(strerror(errno)) + 8); 22 sprintf(buf, "%.3d %s (%s)", code, msg, strerror(errno)); 23 } else { 24 buf = (char *) alloca(strlen(msg) + strlen("XXX ")); 25 sprintf(buf, "%.3d %s", code, msg); 26 } 27 return sendMsg(buf); 28} 29 30int SocketClient::sendMsg(char *msg) { 31 LOGD("SocketClient::sendMsg(%s)", msg); 32 33 if (mSocket < 0) { 34 errno = EHOSTUNREACH; 35 return -1; 36 } 37 38 char *bp; 39 40 if (msg[strlen(msg)] != '\n') { 41 bp = (char *) alloca(strlen(msg) + 1); 42 strcpy(bp, msg); 43 strcat(bp, "\n"); 44 } else 45 bp = msg; 46 47 int rc = 0; 48 char *p = bp; 49 int brtw = strlen(bp); 50 51 pthread_mutex_lock(&mWriteMutex); 52 while(brtw) { 53 if ((rc = write(mSocket,p, brtw)) < 0) { 54 LOGW("Unable to send msg '%s' (%s)", msg, strerror(errno)); 55 pthread_mutex_unlock(&mWriteMutex); 56 return -1; 57 } else if (!rc) { 58 LOGW("0 length write :("); 59 errno = EIO; 60 pthread_mutex_unlock(&mWriteMutex); 61 return -1; 62 } 63 p += rc; 64 brtw -= rc; 65 } 66 pthread_mutex_unlock(&mWriteMutex); 67 return 0; 68} 69