PCMNetClient.cpp
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029 #include "../include/PCMNetClient.h"
00030
00031 namespace ParCompMark
00032 {
00033
00034
00035
00036
00037
00038 NetClient::NetClient(const std::string & name):
00039
00040 Client(name
00041 )
00042 {
00043 getIP();
00044 mOwnIP = mIfConfs->get("eth0")->IP.c_str();
00045 initialize();
00046 }
00047
00048
00049
00050 NetClient::~NetClient()
00051 {
00052 if(mInitialized)
00053 {
00054 finalize();
00055 }
00056 }
00057
00058
00059
00060
00061
00062
00063
00064 void NetClient::initialize()
00065 {
00066
00067 Assert(!mInitialized, INVALID_OPERATION_ERROR, "NetClient::initialize()");
00068
00069
00070
00071 struct sockaddr_in addr;
00072
00073 if((mBroadcastSocket = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
00074 {
00075 Except(INTERNAL_ERROR, "Network::initBroadcastRecieve", "Unable to create socket");
00076 }
00077
00078 addr.sin_family = AF_INET;
00079 addr.sin_addr.s_addr = htonl(INADDR_ANY);
00080 addr.sin_port = htons(mBroadcastPort);
00081 memset(&(addr.sin_zero), '\0', 8);
00082
00083 if(bind(mBroadcastSocket, (struct sockaddr *) &addr, sizeof(struct sockaddr)) < 0)
00084 {
00085 Except(INTERNAL_ERROR, "NetClient::initialize()", "Unable to bind socket");
00086 }
00087
00088 initThread(0, 0, true);
00089
00090 mInitialized = true;
00091
00092 Logger::getInstance()->log(Logger::NOTICE, "NetClient initialized.");
00093 }
00094
00095
00096
00097 void NetClient::finalize()
00098 {
00099 Assert(mInitialized, INVALID_OPERATION_ERROR, "NetClient::finalize()");
00100
00101 if(mBroadcastSocket != -1)
00102 {
00103 close(mBroadcastSocket);
00104 mBroadcastSocket = -1;
00105 }
00106
00107 if(mStreamSocket != -1)
00108 {
00109 close(mStreamSocket);
00110 mStreamSocket = -1;
00111 }
00112
00113 mInitialized = false;
00114
00115 }
00116
00117
00118
00119 void NetClient::task()
00120 {
00121
00122
00123
00124 struct sockaddr_in addr;
00125
00126 unsigned int addrLen = sizeof(struct sockaddr);
00127
00128 int max = 100;
00129
00130 char recvString[max + 1];
00131
00132 int recvStringLen = -1;
00133
00134 if((recvStringLen = recvfrom(mBroadcastSocket, recvString, max, 0, (struct sockaddr *) &addr, &addrLen)) < 0)
00135 {
00136 Except(INTERNAL_ERROR, "NetClient::task()", "Unable to recieve broadcast message");
00137 }
00138
00139
00140 mServerIP = inet_ntoa(addr.sin_addr);
00141
00142 recvString[recvStringLen] = '\0';
00143
00144 std::string message = recvString;
00145
00146 int index = message.find("|");
00147
00148 std::string type = message.substr(0, index);
00149
00150 std::string m = message.substr(index + 1);
00151 m = m.substr(0, m.length());
00152
00153 mType = type;
00154 mMessage = m;
00155
00156 handleMessage();
00157
00158 }
00159
00160
00161
00162 }