IOStream *createRenderThread(int p_stream_buffer_size, unsigned int clientFlags) { SocketStream* stream = NULL; if (gRendererStreamMode == STREAM_MODE_TCP) { stream = new TcpStream(p_stream_buffer_size); } else { #ifdef _WIN32 stream = new Win32PipeStream(p_stream_buffer_size); #else /* !_WIN32 */ stream = new UnixStream(p_stream_buffer_size); #endif } if (!stream) { ERR("createRenderThread failed to create stream\n"); return NULL; } if (stream->connect(s_renderAddr) < 0) { ERR("createRenderThread failed to connect\n"); delete stream; return NULL; } // // send clientFlags to the renderer // unsigned int *pClientFlags = (unsigned int *)stream->allocBuffer(sizeof(unsigned int)); *pClientFlags = clientFlags; stream->commitBuffer(sizeof(unsigned int)); return stream; }
int Iterative_Server::handleData( SocketStream & ss) { ss.recv(); if(strlen(ss.readbuf)>0) { memcpy(ss.sendbuf, ss.readbuf,strlen(ss.readbuf)); ss.readbuf[0]=0; } ss.send(); ss.sclose(); return 0; }
void SocketListen::Loop(long cur_time) { vector<Message*>* vm = send_queue_.GetMessage(); for (int i = 0; i < (*vm).size(); ++i) { Message* msg = (*vm)[i]; if (!msg) continue; MsgHeader header; msg->WriteOut(header); SocketStream* ss = SocketStreamMgr::Instance().Get(header.ip, header.id); if (ss) ss->BufferEventWrite(msg->Data(), msg->Len()); delete msg; } (*vm).clear(); }
int SocketConnector::connect(SocketStream &stream, InetAddr const &addr, size_t) { Handle ret = ::connect(_handle, addr, addr.getSize()); if (ret == INVALID_HANDLE) return -1; stream.setHandle(_handle); return 0; }
void connect() { #if CONNECT // connect to network simulator assert(m_channel.connect() == 0); // send request to initialize InitializeReqMsg req; InitializeResMsg res; m_channel << req >> res; #endif }
void beginflush() { if(writing)return; write_n=sendbuffer.BeginDequeue(); if(write_n==-1) return; writing=true; st.BeginWrite(sendbuffer.GetPointer(write_n), Stream::Callback([this](void* v, Stream* s) { sendbuffer.EndDequeue(write_n); writing=false; beginflush(); })); }
void SocketListen::OnAccept(int fd) { struct sockaddr_in sin; socklen_t len = sizeof(sin); int socket_fd = accept(fd, (struct sockaddr*)&sin, &len); string ip = inet_ntoa(sin.sin_addr); //std::cout << __func__ <<" "<<ip<<" "<<"port: "<<sin.sin_port <<" socket_fd = "<<socket_fd<< std::endl; if (socket_fd == INVALID_SOCKET || socket_fd == SOCKET_ERROR) { std::cout << __func__<< " listen error errno = "<< errno << std::endl; return ; } evutil_make_socket_nonblocking(socket_fd); SocketStream* ss = SocketStreamMgr::Instance().Add(sin.sin_addr.s_addr, queue_); if (!ss) return ; ss->SetIsShortConnect(is_short_connnect_); ss->SetSocketFd(socket_fd); ss->buffer_event_ = bufferevent_new(socket_fd, SocketStream::OnReadCb, SocketStream::OnWriteCb, SocketStream::OnErrorCb,ss); bufferevent_base_set(base_, ss->buffer_event_); bufferevent_enable(ss->buffer_event_, EV_READ | EV_WRITE); ss->Connected(); }
char *WebClient::executeWebMethod( char *inMethod, char *inURL, int *outContentLength, char **outFinalURL, char **outMimeType, long inTimeoutInMilliseconds ) { char *returnString = NULL; if (outFinalURL) *outFinalURL = NULL; char *startString = "http://"; char *urlCopy = strdup( inURL ); char *urlStart = stringLocateIgnoreCase( urlCopy, startString ); char *serverStart; if( urlStart == NULL ) { // no http:// at start of URL serverStart = urlCopy; } else { serverStart = &( urlStart[ strlen( startString ) ] ); } // find the first occurrence of "/", which is the end of the // server name char *serverNameCopy = strdup( serverStart ); char *serverEnd = strstr( serverNameCopy, "/" ); char *getPath = strstr( serverStart, "/" ); if( serverEnd == NULL ) { serverEnd = &( serverStart[ strlen( serverStart ) ] ); getPath = "/"; } // terminate the url here to extract the server name serverEnd[0] = '\0'; int portNumber = 80; // look for a port number char *colon = strstr( serverNameCopy, ":" ); if( colon != NULL ) { char *portNumberString = &( colon[1] ); int numRead = sscanf( portNumberString, "%d", & portNumber ); if( numRead != 1 ) { portNumber = 80; } // terminate the name here so port isn't taken as part // of the address colon[0] = '\0'; } HostAddress *host = new HostAddress( strdup( serverNameCopy ), portNumber ); // will be set to true if we time out while connecting char timedOut; Socket *sock = SocketClient::connectToServer( host, inTimeoutInMilliseconds, &timedOut ); char *finalURL = strdup( inURL ); char *mimeType = NULL; int receivedLength = 0; if( sock != NULL ) { SocketStream *stream = new SocketStream( sock ); // reuse the same timeout for read operations stream->setReadTimeout( inTimeoutInMilliseconds ); // method and trailing space need to be sent in the same // buffer to work around a bug in certain web servers char *methodWithSpace = new char[ strlen( inMethod ) + 2 ]; sprintf( methodWithSpace, "%s ", inMethod ); // send the request stream->writeString( methodWithSpace ); stream->writeString( getPath ); stream->writeString( " HTTP/1.0\r\n" ); stream->writeString( "Host: " ); stream->writeString( serverNameCopy ); stream->writeString( "\r\n\r\n" ); delete [] methodWithSpace; // the simplest thing to do is to read upto the // socket close first, then extract the content char *received = receiveData( stream, &receivedLength ); char *content = NULL; char notFound = false; if( stringLocateIgnoreCase ( received, "404 Not Found" ) != NULL ) { notFound = true; } // watch for redirection headers if( stringLocateIgnoreCase( received, "302 Found" ) != NULL || stringLocateIgnoreCase( received, "301 Moved Permanently" ) != NULL || stringLocateIgnoreCase( received, "302 Object Moved" ) != NULL ) { // call ourself recursively to fetch the redirection char *locationTag = "Location: "; char *locationTagStart = stringLocateIgnoreCase( received, locationTag ); if( locationTagStart != NULL ) { char *locationStart = &( locationTagStart[ strlen( locationTag ) ] ); // replace next \r with \0 char *nextChar = locationStart; while( nextChar[0] != '\r' && nextChar[0] != '\0' ) { nextChar = &( nextChar[1] ); } nextChar[0] = '\0'; char *newFinalURL=NULL; if (strcmp(inURL,locationStart)) content = getWebPage( locationStart, &receivedLength, &newFinalURL, &mimeType ); delete [] locationTagStart; delete [] finalURL; finalURL = newFinalURL; if( content == NULL ) { // not found recursively notFound = true; } } } char *contentStartString = "\r\n\r\n"; char *contentTypeStartString = "Content-type:"; if( notFound ) { returnString = NULL; } else { if( content == NULL ) { // scan for content type char *contentTypeStartMarker = stringLocateIgnoreCase( received, contentTypeStartString ); if( contentTypeStartMarker != NULL ) { // skip marker char *contentTypeStart = &( contentTypeStartMarker[ strlen( contentTypeStartString ) ] ); // extract content type // make sure the buffer is big enough char *contentType = new char[ strlen( contentTypeStartMarker ) ]; int numRead = sscanf( contentTypeStart, "%s", contentType ); if( numRead == 1 ) { // trim mimeType = strdup( contentType ); } delete [] contentType; delete [] contentTypeStartMarker; } // extract the content from what we've received char *contentStart = strstr( received, contentStartString ); if( contentStart != NULL ) { content = &( contentStart[ strlen( contentStartString ) ] ); receivedLength = receivedLength - strlen( contentStartString ) - ( (long)(contentStart - received) ); returnString = new char[ receivedLength + 1 ]; returnString = (char*)memcpy( returnString, content, receivedLength ); returnString[ receivedLength ] = '\0'; } } else { // we already obtained our content recursively returnString = new char[ receivedLength + 1 ]; returnString = (char*)memcpy( returnString, content, receivedLength ); returnString[ receivedLength ] = '\0'; delete [] content; } } delete [] received; delete stream; delete sock; } delete host ; free ( serverNameCopy ) ; free ( urlCopy ) ; if( outFinalURL != NULL ) { *outFinalURL = finalURL; } else { free ( finalURL ) ; } if( outMimeType != NULL ) { *outMimeType = mimeType; } else { if( mimeType != NULL ) { free ( mimeType ) ; } } *outContentLength = receivedLength; return returnString; }
int main() { char *name = new char[99]; sprintf( name, "63.249.65.249" ); //char *name = new char[99]; //sprintf( name, "192.168.1.2" ); //char *name = "192.168.1.1"; //int addressLength = 11; //char *name = "monolith.2y.net"; //int addressLength = 15; int port = 5158; HostAddress *address = new HostAddress( name, port ); printf( "Trying to connect to server: " ); address->print(); printf( "\n" ); Socket *sock; int numConnections = 0; while( true ) { sock = SocketClient::connectToServer( address ); if( sock == NULL ) { printf( "%d Connecting to server failed\n", numConnections ); //return 1; } else { printf( "%d Connection established\n", numConnections ); HostAddress *localAddress = sock->getLocalHostAddress(); if( localAddress != NULL ) { printf( "Our local address (fetched from socket) is " ); localAddress->print(); printf( "\n" ); delete localAddress; } delete sock; } //usleep( 1000 ); numConnections++; } int numBytes = 4000; unsigned char *buffer = new unsigned char[numBytes]; for( int i=0; i<numBytes; i++ ) { buffer[i] = i; } SocketStream *stream = new SocketStream( sock ); //printf( "sleeping\n" ); //sleep( 10 ); int count = 0; while( true ) { printf( "sending %d bytes\n", numBytes ); int numSent = stream->write( buffer, numBytes ); printf( "Sent %d successfully,\tcount = %d\n", numSent, count ); count++; } int checksum = 0; for( int i=0; i<numBytes; i++ ) { checksum += buffer[ i ]; } printf( "Checksum: %d\n", checksum ); printf( "Deleting stream\n" ); delete stream; printf( "Deleting socket\n" ); delete sock; printf( "Deleting address\n" ); delete address; printf( "Returning\n" ); return 0; }
int RenderServer::Main() { RenderThreadsSet threads; while(1) { SocketStream *stream = m_listenSock->accept(); if (!stream) { fprintf(stderr,"Error accepting connection, aborting\n"); break; } unsigned int clientFlags; if (!stream->readFully(&clientFlags, sizeof(unsigned int))) { fprintf(stderr,"Error reading clientFlags\n"); delete stream; continue; } DBG("\n\n\n\n Got new stream!!!! \n\n\n\n\n"); // check if we have been requested to exit while waiting on accept if ((clientFlags & IOSTREAM_CLIENT_EXIT_SERVER) != 0) { m_exiting = true; break; } RenderThread *rt = RenderThread::create(stream); if (!rt) { fprintf(stderr,"Failed to create RenderThread\n"); delete stream; } if (!rt->start()) { fprintf(stderr,"Failed to start RenderThread\n"); delete stream; delete rt; } // // remove from the threads list threads which are // no longer running // for (RenderThreadsSet::iterator n,t = threads.begin(); t != threads.end(); t = n) { // first find next iterator n = t; n++; // delete and erase the current iterator // if thread is no longer running if ((*t)->isFinished()) { delete (*t); threads.erase(t); } } // insert the added thread to the list threads.insert(rt); DBG("Started new RenderThread\n"); } // // Wait for all threads to finish // for (RenderThreadsSet::iterator t = threads.begin(); t != threads.end(); t++) { int exitStatus; (*t)->wait(&exitStatus); delete (*t); } threads.clear(); // // de-initialize the FrameBuffer object // FrameBuffer::finalize(); return 0; }
int main(int argc, const char *argv[]) { int returnCode = 0; MAINHELPER_SETUP_MEMORY_LEAK_EXIT_REPORT("bbackupctl.memleaks", "bbackupctl") MAINHELPER_START Logging::SetProgramName("bbackupctl"); // Filename for configuration file? std::string configFilename = BOX_GET_DEFAULT_BBACKUPD_CONFIG_FILE; // See if there's another entry on the command line int c; std::string options("c:"); options += Logging::OptionParser::GetOptionString(); Logging::OptionParser LogLevel; while((c = getopt(argc, (char * const *)argv, options.c_str())) != -1) { switch(c) { case 'c': // store argument configFilename = optarg; break; default: int ret = LogLevel.ProcessOption(c); if(ret != 0) { PrintUsageAndExit(ret); } } } // Adjust arguments argc -= optind; argv += optind; // Check there's a command if(argc != 1) { PrintUsageAndExit(2); } Logging::FilterConsole(LogLevel.GetCurrentLevel()); // Read in the configuration file BOX_INFO("Using configuration file " << configFilename); std::string errs; std::auto_ptr<Configuration> config( Configuration::LoadAndVerify (configFilename, &BackupDaemonConfigVerify, errs)); if(config.get() == 0 || !errs.empty()) { BOX_ERROR("Invalid configuration file: " << errs); return 1; } // Easier coding const Configuration &conf(*config); // Check there's a socket defined in the config file if(!conf.KeyExists("CommandSocket")) { BOX_ERROR("Daemon isn't using a control socket, " "could not execute command.\n" "Add a CommandSocket declaration to the " "bbackupd.conf file."); return 1; } // Connect to socket #ifndef WIN32 SocketStream connection; #else /* WIN32 */ WinNamedPipeStream connection; #endif /* ! WIN32 */ try { #ifdef WIN32 std::string socket = conf.GetKeyValue("CommandSocket"); connection.Connect(socket); #else connection.Open(Socket::TypeUNIX, conf.GetKeyValue("CommandSocket").c_str()); #endif } catch(...) { BOX_ERROR("Failed to connect to daemon control socket.\n" "Possible causes:\n" " * Daemon not running\n" " * Daemon busy syncing with store server\n" " * Another bbackupctl process is communicating with the daemon\n" " * Daemon is waiting to recover from an error" ); return 1; } // For receiving data IOStreamGetLine getLine(connection); // Wait for the configuration summary std::string configSummary; if(!getLine.GetLine(configSummary, false, PROTOCOL_DEFAULT_TIMEOUT)) { BOX_ERROR("Failed to receive configuration summary " "from daemon"); return 1; } // Was the connection rejected by the server? if(getLine.IsEOF()) { BOX_ERROR("Server rejected the connection. Are you running " "bbackupctl as the same user as the daemon?"); return 1; } // Decode it int autoBackup, updateStoreInterval, minimumFileAge, maxUploadWait; if(::sscanf(configSummary.c_str(), "bbackupd: %d %d %d %d", &autoBackup, &updateStoreInterval, &minimumFileAge, &maxUploadWait) != 4) { BOX_ERROR("Config summary didn't decode."); return 1; } // Print summary? BOX_TRACE("Daemon configuration summary:\n" " AutomaticBackup = " << (autoBackup?"true":"false") << "\n" " UpdateStoreInterval = " << updateStoreInterval << " seconds\n" " MinimumFileAge = " << minimumFileAge << " seconds\n" " MaxUploadWait = " << maxUploadWait << " seconds"); std::string stateLine; if(!getLine.GetLine(stateLine, false, PROTOCOL_DEFAULT_TIMEOUT) || getLine.IsEOF()) { BOX_ERROR("Failed to receive state line from daemon"); return 1; } // Decode it int currentState; if(::sscanf(stateLine.c_str(), "state %d", ¤tState) != 1) { BOX_ERROR("Received invalid state line from daemon"); return 1; } BOX_TRACE("Current state: " << BackupDaemon::GetStateName(currentState)); Command command = Default; std::string commandName(argv[0]); if(commandName == "wait-for-sync") { command = WaitForSyncStart; } else if(commandName == "wait-for-end") { command = WaitForSyncEnd; } else if(commandName == "sync-and-wait") { command = SyncAndWaitForEnd; } else if(commandName == "status") { BOX_NOTICE("state " << BackupDaemon::GetStateName(currentState)); command = NoCommand; } switch(command) { case WaitForSyncStart: case WaitForSyncEnd: { // Check that it's in automatic mode, // because otherwise it'll never start if(!autoBackup) { BOX_ERROR("Daemon is not in automatic mode, " "sync will never start!"); return 1; } } break; case SyncAndWaitForEnd: { // send a sync command commandName = "force-sync"; std::string cmd = commandName + "\n"; connection.Write(cmd, PROTOCOL_DEFAULT_TIMEOUT); connection.WriteAllBuffered(); if(currentState != 0) { BOX_INFO("Waiting for current sync/error state " "to finish..."); } } break; default: { // Normal case, just send the command given, plus a // quit command. std::string cmd = commandName + "\n"; connection.Write(cmd, PROTOCOL_DEFAULT_TIMEOUT); } // fall through case NoCommand: { // Normal case, just send the command given plus a // quit command. std::string cmd = "quit\n"; connection.Write(cmd, PROTOCOL_DEFAULT_TIMEOUT); } } // Read the response std::string line; bool syncIsRunning = false; bool finished = false; while(command != NoCommand && !finished && !getLine.IsEOF() && getLine.GetLine(line, false, PROTOCOL_DEFAULT_TIMEOUT)) { BOX_TRACE("Received line: " << line); if(line.substr(0, 6) == "state ") { std::string state_str = line.substr(6); int state_num; if(sscanf(state_str.c_str(), "%d", &state_num) == 1) { BOX_INFO("Daemon state changed to: " << BackupDaemon::GetStateName(state_num)); } else { BOX_WARNING("Failed to parse line: " << line); } } switch(command) { case WaitForSyncStart: { // Need to wait for the state change... if(line == "start-sync") { // And we're done finished = true; } } break; case WaitForSyncEnd: case SyncAndWaitForEnd: { if(line == "start-sync") { BOX_TRACE("Sync started..."); syncIsRunning = true; } else if(line == "finish-sync") { if (syncIsRunning) { // And we're done BOX_TRACE("Sync finished."); finished = true; } else { BOX_TRACE("Previous sync finished."); } // daemon must still be busy } } break; default: { // Is this an OK or error line? if(line == "ok") { BOX_TRACE("Control command " "sent: " << commandName); finished = true; } else if(line == "error") { BOX_ERROR("Control command failed: " << commandName << ". Check " "command spelling."); returnCode = 1; finished = true; } } } } // Send a quit command to finish nicely connection.Write("quit\n", 5, PROTOCOL_DEFAULT_TIMEOUT); MAINHELPER_END #if defined WIN32 && ! defined BOX_RELEASE_BUILD closelog(); #endif return returnCode; }
void testservers_connection(SocketStream &rStream) { IOStreamGetLine getline(rStream); if(typeid(rStream) == typeid(SocketStreamTLS)) { // need to wait for some data before sending stuff, otherwise timeout test doesn't work std::string line; while(!getline.GetLine(line)) ; SocketStreamTLS &rtls = (SocketStreamTLS&)rStream; std::string line1("CONNECTED:"); line1 += rtls.GetPeerCommonName(); line1 += '\n'; testservers_pause_before_reply(); rStream.Write(line1.c_str(), line1.size()); } while(!getline.IsEOF()) { std::string line; while(!getline.GetLine(line)) ; if(line == "QUIT") { break; } if(line == "LARGEDATA") { { // Send lots of data char data[LARGE_DATA_BLOCK_SIZE]; for(unsigned int y = 0; y < sizeof(data); y++) { data[y] = y & 0xff; } for(int s = 0; s < (LARGE_DATA_SIZE / LARGE_DATA_BLOCK_SIZE); ++s) { rStream.Write(data, sizeof(data), SHORT_TIMEOUT); } } { // Receive lots of data char buf[1024]; int total = 0; int r = 0; while(total < LARGE_DATA_SIZE && (r = rStream.Read(buf, sizeof(buf), SHORT_TIMEOUT)) != 0) { total += r; } TEST_THAT(total == LARGE_DATA_SIZE); if (total != LARGE_DATA_SIZE) { BOX_ERROR("Expected " << LARGE_DATA_SIZE << " bytes " << "but was " << total); return; } } { // Send lots of data again char data[LARGE_DATA_BLOCK_SIZE]; for(unsigned int y = 0; y < sizeof(data); y++) { data[y] = y & 0xff; } for(int s = 0; s < (LARGE_DATA_SIZE / LARGE_DATA_BLOCK_SIZE); ++s) { rStream.Write(data, sizeof(data), SHORT_TIMEOUT); } } // next! continue; } std::string backwards; for(std::string::const_reverse_iterator i(line.end()); i != std::string::const_reverse_iterator(line.begin()); ++i) { backwards += (*i); } backwards += '\n'; testservers_pause_before_reply(); rStream.Write(backwards.c_str(), backwards.size()); } rStream.Shutdown(); rStream.Close(); }
int main( char inNumArgs, char **inArgs ) { if( inNumArgs < 2 ) { usage( inArgs[0] ); } if( inNumArgs > 3 ) { usage( inArgs[0] ); } char useFile = true; if( inNumArgs != 3 ) { useFile = false; } long port; int numRead = sscanf( inArgs[1], "%d", &port ); if( numRead != 1 ) { printf( "port number must be a valid integer: %s\n", inArgs[2] ); usage( inArgs[0] ); } File *outFile; FileOutputStream *outStream; if( useFile ) { outFile = new File( NULL, inArgs[2], strlen( inArgs[2] ) ); outStream = new FileOutputStream( outFile ); } SocketServer *server = new SocketServer( port, 1 ); printf( "listening for a connection on port %d\n", port ); Socket *sock = server->acceptConnection(); if( sock == NULL ) { printf( "socket connection failed\n" ); return( 1 ); } printf( "connection received\n" ); SocketStream *inStream = new SocketStream( sock ); unsigned long checksum = 0; unsigned char *buffer = new unsigned char[ BUFFER_SIZE ]; numRead = BUFFER_SIZE; int numWritten = BUFFER_SIZE; while( numWritten == numRead && numRead == BUFFER_SIZE ) { // read a buffer full of data from standard in numRead = inStream->read( buffer, BUFFER_SIZE ); // add the buffer to our checksum for( int i=0; i<numRead; i++ ) { checksum += buffer[i]; } if( useFile ) { // write the buffer out to our file stream numWritten = outStream->write( buffer, numRead ); } else { // write to std out numWritten = fwrite( buffer, 1, numRead, stdout ); } } if( numRead != numWritten ) { printf( "file output failed\n" ); } printf( "checksum = %d\n", checksum ); delete sock; delete server; delete inStream; if( useFile ) { delete outStream; delete outFile; } delete [] buffer; return 0; }
void Server::run() { _server.bind(_port); _server.listen(_queueSize); network::Socket::Select select; std::list< SocketStream* >::iterator it; LOG_INFO << "Starting server on port " << _port << std::endl; try { signal(SIGINT, sigpass); signal(SIGPIPE, SIG_IGN); while (true) { select.zero(network::ISocket::Select::READ); select.zero(network::ISocket::Select::WRITE); select.set(&_server, network::ISocket::Select::READ); std::list< SocketStream* > toDelete; for (it = _clients.begin(); it != _clients.end(); ++it) { network::ISocket* s = (*it)->socket(); if (s) { select.set(s, network::ISocket::Select::READ); select.set(s, network::ISocket::Select::WRITE); } else if ((*it)->closed()) toDelete.push_back(*it); } for (it = toDelete.begin(); it != toDelete.end(); ++it) { LOG_INFO << "Closing connection:\t" << *it << std::endl; _clients.remove(*it); (*it)->deleteLater(); } select.run(); if (select.isSet(&_server, network::ISocket::Select::READ)) { SocketStream* client = new SocketStream(_server.accept(), _readSize); _clients.push_back(client); LOG_INFO << "Getting new connection:\t" << client << std::endl; client->contextEmit(client->uuid().str(), _sigNewClient, _sigReadClient.data()); } for (it = _clients.begin(); it != _clients.end(); ++it) { if ((*it)->socket() && select.isSet((*it)->socket(), network::ISocket::Select::READ)) { LOG_DEBUG << "Read on client\t" << *it << std::endl; try { (*it)->readBuff(); (*it)->contextEmit((*it)->uuid().str(), _sigReadClient); } catch (network::ISocket::Exception& e) { e.log(); (*it)->close(); } } if ((*it)->socket() && select.isSet((*it)->socket(), network::ISocket::Select::WRITE)) { try { (*it)->writeBuff(); } catch (network::ISocket::Exception& e) { e.log(); (*it)->close(); } } } } } catch (network::ISocket::Select::Exception& e) { e.log(); } catch (utils::Interrupt& e) { e.log(); } }
int main(int argc, char* argv[]) { ArgumentParser argParser(argc, argv); char buffer[TAM_BUFFER]; char bufferSocket[TAM_BUFFER]; int socketDescriptor = 0; int brokerNumber = 0; int remoteBrokerId = 0; if ( argParser.parseArgument(1, socketDescriptor) == -1 ) { Logger::logMessage(Logger::ERROR, "ERROR: Parse Argument 1."); exit(-1); } if ( argParser.parseArgument(2, brokerNumber) == -1 ) { Logger::logMessage(Logger::ERROR, "ERROR: Parse Argument 2."); exit(-1); } if ( argc == 4 && socketDescriptor == 0 ) { if ( argParser.parseArgument(3, remoteBrokerId) == -1 ) { Logger::logMessage(Logger::ERROR, "ERROR: Parse Argument 3."); exit(-1); } } elegirDirectorios( brokerNumber ); sprintf(buffer, "CanalSalidaBrokerBroker N°%d - N°%d:", brokerNumber, remoteBrokerId); Logger::setProcessInformation(buffer); SocketStream* socketBroker = NULL; if ( socketDescriptor == 0 ) { sprintf(buffer, "Creando conexión con Broker N°%d", remoteBrokerId); Logger::logMessage(Logger::DEBUG, buffer); // El proceso no fue creado por un servidor, debe conectarse al // mismo ServersManager serversManager; socketBroker = serversManager.connectToBrokerServer( "ServidorCanalEntradaBrokerBroker", remoteBrokerId); if ( socketBroker == NULL ) { abort(); } // Envía al otro extremo del canal su número de Broker memcpy(bufferSocket, &brokerNumber, sizeof(int)); if ( socketBroker->send(bufferSocket, TAM_BUFFER) != TAM_BUFFER ) { Logger::logMessage(Logger::ERROR, "Error al envíar brokerNumber por el Socket"); socketBroker->destroy(); abort(); } } else { // El proceso fue creado por un servidor SocketStream aux( socketDescriptor ); socketBroker = &aux; // Recibe el número de Broker con el cual se conectó if ( socketBroker->receive(bufferSocket, TAM_BUFFER) != TAM_BUFFER ) { Logger::logMessage(Logger::ERROR, "Error al recibir brokerNumber por el Socket"); socketBroker->destroy(); abort(); } memcpy(& remoteBrokerId, bufferSocket, sizeof(int)); } sprintf(buffer, "CanalSalidaBrokerBroker N°%d - N°%d:", brokerNumber, remoteBrokerId); Logger::setProcessInformation(buffer); Logger::logMessage(Logger::COMM, "Conexión realizada correctamente"); try { IPC::MsgQueue colaCanalSalida("ColaCanalSalida"); colaCanalSalida.getMsgQueue(C_DIRECTORY_BROKER, ID_MSG_QUEUE_CSBB); while ( true ) { MsgCanalSalidaBrokerBroker mensaje; colaCanalSalida.recv(remoteBrokerId, mensaje); Logger::logMessage(Logger::COMM, "Recibe mensaje, procede a enviarlo"); memcpy(bufferSocket, &mensaje.msg, sizeof(MsgCanalEntradaBrokerBroker)); if ( socketBroker->send(bufferSocket, TAM_BUFFER) != TAM_BUFFER ) { Logger::logMessage(Logger::ERROR, "Error al enviar mensaje a Broker"); socketBroker->destroy(); abort(); } } } catch( Exception & e) { Logger::logMessage(Logger::ERROR, e.get_error_description()); socketBroker->destroy(); if (socketDescriptor == 0) { delete socketBroker; } abort(); } Logger::logMessage(Logger::COMM, "Destruyendo canal"); socketBroker->destroy(); if (socketDescriptor == 0) { delete socketBroker; } return 0; }