bool Camera_INDIClass::Connect(const wxString& camId) { // If not configured open the setup dialog if (strcmp(INDICameraName,"INDI Camera")==0) CameraSetup(); // define server to connect to. setServer(INDIhost.mb_str(wxConvUTF8), INDIport); // Receive messages only for our camera. watchDevice(INDICameraName.mb_str(wxConvUTF8)); // Connect to server. if (connectServer()) { return !ready; } else { // last chance to fix the setup CameraSetup(); setServer(INDIhost.mb_str(wxConvUTF8), INDIport); watchDevice(INDICameraName.mb_str(wxConvUTF8)); if (connectServer()) { return !ready; } else { return true; } } }
bool ScopeINDI::Connect() { // If not configured open the setup dialog if (INDIMountName == wxT("INDI Mount")) { SetupDialog(); } // define server to connect to. setServer(INDIhost.mb_str(wxConvUTF8), INDIport); // Receive messages only for our mount. watchDevice(INDIMountName.mb_str(wxConvUTF8)); // Connect to server. if (connectServer()) { return !ready; } else { // last chance to fix the setup SetupDialog(); setServer(INDIhost.mb_str(wxConvUTF8), INDIport); watchDevice(INDIMountName.mb_str(wxConvUTF8)); if (connectServer()) { return !ready; } else { return true; } } }
void IOToaster::setup() { // Set the pin configuration setupPins(); // Open serial communication Serial.begin(9600); Serial.setTimeout(5000); // Load the configuration if (isConfigured()) { // Normal mode _setupMode = false; loadConfiguration(); connectServer(); setActivityLedState(HIGH); } else { // Setup mode setActivityLedState(LOW); _setupMode = true; createServer(); } }
void SocketSender::sendLog(std::list<MLogRec> &logs) throw(SendException) { readFailFile(logs); connectServer(); sendData(logs); saveFailFile(logs); }
int main(void) { //Diccionario de funciones de comunicacion fns = dictionary_create(); dictionary_put(fns, "server_saludar", &server_saludar); //Creo estrucutra de datos para esta conexion data_client * data = malloc(sizeof(data_client)); data->x = 2; data->y = 9; //Me conecto a servidor, si hay error informo y finalizo if((socket_server = connectServer(ip, port, fns, &server_connectionClosed, data)) == -1) { printf("Error al intentar conectar a servidor. IP = %s, Puerto = %d.\n", ip, port); exit(1); } printf("Se ha conectado exitosamente a servidor. Socket = %d, IP = %s, Puerto = %d.\n", socket_server, ip, port); //saludo a servidor runFunction(socket_server, "client_saludar", 3, "hola", "como", "estas"); //Dejo bloqueado main pthread_mutex_init(&mx_main, NULL); pthread_mutex_lock(&mx_main); pthread_mutex_lock(&mx_main); return EXIT_SUCCESS; }
int CSocketClient::start(int nSocketType, const char* cszAddr, short nPort, int nStyle) { if (AF_UNIX == nSocketType) { setDomainSocketPath(cszAddr); } else if (AF_INET == nSocketType) { if (-1 == setInetSocket(cszAddr, nPort)) { _DBG("set INET socket address & port fail"); return -1; } } if (-1 != createSocket(nSocketType, nStyle)) { if (SOCK_STREAM == nStyle) { if (-1 == connectServer()) { socketClose(); return -1; } } _DBG("[Socket Client] Socket connect success"); return getSocketfd(); } return -1; }
/* * ftpc program sends the target file * to the server specified by the user * with ip address and port number. */ int main(int argc, char *argv[]) { int sockfd = -1; // precheck arguments if(preCheckArgs(argc, argv) == -1) { exit(-1); } // create the socket sockfd = socket(AF_INET, SOCK_STREAM, 0); if(sockfd < 0) { fprintf(stderr, "ftpc: ERROR: Can't create the socket.\n"); exit(-1); } // connect to the server if(connectServer(sockfd, /*ip address*/argv[1], /*port*/argv[2]) < 0) { exit(-1); } // send the file to the server sendFileToServer(sockfd, argv[3]); return 0; }
int ESP8266_XYZ::httpGet(const char* server, String path, int port, String *response){ String msg = ""; String server_str = server; if(connectServer(server, port)){ #ifdef DEBUG Serial.println("Connected to server"); #endif } else { #ifdef DEBUG Serial.println("Connection Failure"); #endif } server_str += ":"; server_str += String(port); //GET HTTP/1.1\r\nHost: \r\n\r\n //Solicitud HTTP al servidor //Header msg += "GET "; msg += path; msg += " HTTP/1.1\r\nHost: "; msg += server_str; msg += "\r\n\r\n"; //Se envía el mensaje al servidor client.print(msg); //Se obtiene el código de estado de la solicitud return readResponse(response); }
void MainWindow::changeServerStatus(bool s) { if(s) connectServer(); else disconnectServer(); }
int FClient::requestID(const char *desc) { int socketfd; unsigned char buf[128]; int i; unsigned int uret; FILE *f; int hid; hid = gethostid(); /* connect to the server */ socketfd = connectServer(); if (socketfd<0) { return 0; } /* send the request */ sendMessage(socketfd,"",FGETMACHINEID); /* read the id */ uret = readU32(socketfd); /* close the socket */ close(socketfd); return uret; }
int FClient::sendFile(const char *fname) { int socketfd; unsigned char buf[128]; int i; unsigned int hashval; FILE *f; /* connect to the server */ socketfd = connectServer(); if (socketfd<0) { return 0; } /* send the request */ sendMessage(socketfd,fname,FSENDFILE); /* send the file */ writeFile(fname,socketfd); /* close the socket */ close(socketfd); return 1; }
void RSocketServer::onRSocketSetup( std::shared_ptr<RSocketServiceHandler> serviceHandler, std::shared_ptr<ConnectionSet> connectionSet, bool scheduledResponder, std::unique_ptr<DuplexConnection> connection, SetupParameters setupParams) { const auto eventBase = folly::EventBaseManager::get()->getExistingEventBase(); VLOG(2) << "Received new setup payload on " << eventBase->getName(); CHECK(eventBase); auto result = serviceHandler->onNewSetup(setupParams); if (result.hasError()) { VLOG(3) << "Terminating SETUP attempt from client. " << result.error().what(); connection->send( FrameSerializer::createFrameSerializer(setupParams.protocolVersion) ->serializeOut(Frame_ERROR::rejectedSetup(result.error().what()))); return; } auto connectionParams = std::move(result.value()); if (!connectionParams.responder) { LOG(ERROR) << "Received invalid Responder. Dropping connection"; connection->send( FrameSerializer::createFrameSerializer(setupParams.protocolVersion) ->serializeOut(Frame_ERROR::rejectedSetup( "Received invalid Responder from server"))); return; } const auto rs = std::make_shared<RSocketStateMachine>( scheduledResponder ? std::make_shared<ScheduledRSocketResponder>( std::move(connectionParams.responder), *eventBase) : std::move(connectionParams.responder), nullptr, RSocketMode::SERVER, connectionParams.stats, std::move(connectionParams.connectionEvents), setupParams.resumable ? std::make_shared<WarmResumeManager>(connectionParams.stats) : ResumeManager::makeEmpty(), nullptr /* coldResumeHandler */); if (!connectionSet->insert(rs, eventBase)) { VLOG(1) << "Server is closed, so ignore the connection"; connection->send( FrameSerializer::createFrameSerializer(setupParams.protocolVersion) ->serializeOut(Frame_ERROR::rejectedSetup( "Server ignores the connection attempt"))); return; } rs->registerCloseCallback(connectionSet.get()); auto requester = std::make_shared<RSocketRequester>(rs, *eventBase); auto serverState = std::shared_ptr<RSocketServerState>( new RSocketServerState(*eventBase, rs, std::move(requester))); serviceHandler->onNewRSocketState(std::move(serverState), setupParams.token); rs->connectServer( std::make_shared<FrameTransportImpl>(std::move(connection)), std::move(setupParams)); }
// Initialize Networking Sockets void initPeerSocket(void) { #ifdef SERVERMODE fdPeerSock = acceptClient(); #endif #ifdef CLIENTMODE fdPeerSock = connectServer(); #endif }
void initRemoteDebugging() { WORD ver = MAKEWORD(1, 1); WSADATA data; WSAStartup(ver, &data); debugEventSocket = connectServer("127.0.0.1", 1523); if (debugEventSocket < 0) debugEventSocket = 0; }
bool SocketTest::init() { if (!Layer::init()) { return false; } connectServer(); return true; }
void FClient::requestFileListRebuild() { unsigned int socketfd; /* connect to the server */ socketfd = connectServer(); /* send the message */ sendMessage(socketfd,"",FREQUESTDIRLISTING); }
void INDIConfig::Connect() { dev->Clear(); Disconnect(); INDIhost = host->GetLineText(0); port->GetLineText(0).ToLong(&INDIport); setServer(INDIhost.mb_str(wxConvUTF8), INDIport); if (connectServer()) { connect_status->SetLabel(_T("Connected")); } }
void * threadStart(void *arg) { int server_fd = connectServer(server_info.address, server_info.port); if(server_fd == -1) pthread_exit((void *)-1); test(server_fd); close(server_fd); pthread_exit((void *)0); }
int startDataSocket(int socket, char *msg) { int sockdata = 0; int port = convertPortNo(msg); char ip[strlen(msg)]; char *address; int i = 0, count = 0, n = 0; char recvBuff[1024]; char filename[100]="fileName\n"; /* * * * * * * CONVERT PASV MESSAGE TO IP ADDRESS * */ strcpy(ip, msg); while (ip[i] != '\0') { if (ip[i] == ',') { ip[i] = '.'; count++; } if (count == 4) { ip[i] = '\0'; } i++; } i = 0; count = 0; address = ip + 1; //printf("\n Creating Data Socket... \n"); //printf("\n portno:%i", port); //printf("\n Connecting Data Socket To Server... \n"); n = connectServer(socket, address, port); if (n < 0) { printf("%s\n", strerror(errno)); exit(1); } return n; }
int OSGScaleViewer::run() { // 1. connect to server eq::ServerPtr server = new eq::Server(); if( !connectServer( server )) { EQERROR << "Can't open server" << std::endl; return EXIT_FAILURE; } // 2. choose config eq::ConfigParams configParams; Config* config = static_cast<Config*>( server->chooseConfig( configParams)); if( !config ) { EQERROR << "No matching config on server" << std::endl; disconnectServer( server ); return EXIT_FAILURE; } config->setInitData( _initData ); if( !config->init( )) { server->releaseConfig( config ); disconnectServer( server ); return EXIT_FAILURE; } else if( config->getError( )) EQWARN << "Error during initialization: " << config->getError() << std::endl; // 4. run main loop while( config->isRunning( )) { config->startFrame(); config->finishFrame(); } config->finishAllFrames(); // 5. exit config config->exit(); // 6. cleanup and exit server->releaseConfig( config ); if( !disconnectServer( server )) EQERROR << "Client::disconnectServer failed" << std::endl; server = 0; return EXIT_SUCCESS; }
bool TServerList::onRecv() { // Grab the data from the socket and put it into our receive buffer. unsigned int size = 0; char* data = sock.getData(&size); if (size != 0) rBuffer.write(data, size); if (!main()) connectServer(); return true; }
Client::Client(const int argc, char** argv, const bool isResident) : _impl(new Client::Impl(isResident)) { if (!initLocal(argc, argv)) LBTHROW(std::runtime_error("Can't init client")); _impl->server = new eq::Server; if (!connectServer(_impl->server)) { exitLocal(); LBTHROW(std::runtime_error("Can't open server")); } }
int TVUClient::recvPackage(int &flag) { if(m_pChannel == NULL) { //连接服务器 if(connectServer()<1) { flag = TVU_ERROR_SERVER_NOT_OPEN; return NULL; } } return m_pChannel->recvPackage(flag); }
int main (int argc, char *argv[argc + 1]) { initThreadRunning (); int32_t *theMotherOfAllRequests = malloc (sizeof (int32_t) * 5); if (theMotherOfAllRequests == NULL) { printf ("memory is kill\n"); exit (-1); } theMotherOfAllRequests[0] = BEGIN; theMotherOfAllRequests[1] = num_resources; theMotherOfAllRequests[2] = num_clients; theMotherOfAllRequests[3] = -1; theMotherOfAllRequests[4] = -1; int begin_fd = connectServer (); if (send_request (0, 0, begin_fd, theMotherOfAllRequests) == -1) { printf ("The server said screw you\n"); exit (-1); } shutdown (begin_fd, 0); close (begin_fd); client_thread client_threads[NUM_CLIENTS]; for (unsigned int i = 0; i < num_clients; i++) { ct_init (&(client_threads[i])); } ct_wait_server (); // Affiche le journal. st_print_results (stdout, true); FILE *fp = fopen ("client_log", "w"); if (fp == NULL) { fprintf (stderr, "Could not print log"); return EXIT_FAILURE; } st_print_results (fp, false); fclose (fp); return EXIT_SUCCESS; }
int ESP8266_XYZ::httpPost(const char* server, String path, int port, String *response){ String msg = ""; String server_str = server; if(connectServer(server, port)){ #ifdef DEBUG Serial.println("Connected to server"); #endif } else { #ifdef DEBUG Serial.println("Connection Failure"); #endif return -1; } server_str += ":"; server_str += String(port); //Cálculo de lengitud total del mensaje uint16_t json_len = json.length(); json.setCharAt(json_len-1, '}'); //POST HTTP/1.1\r\nHost: \r\nConnection: close\r\nAccept: application/json\r\nContent-Type: application/json\r\nContent-Length:\r\n\r\n //Solicitud HTTP al servidor //Header msg += "POST "; msg += path; msg += " HTTP/1.1\r\nHost: "; msg += server_str; msg += "\r\nConnection: close\r\n"; msg += "Accept: application/json\r\n"; msg += "Content-Type: application/json\r\nContent-Length:"; msg += json_len; msg += "\r\n\r\n"; msg += json; #ifdef DEBUG Serial.print("Request: "); Serial.println(msg); #endif client.print(msg); //Reestablece el JSON para el siguiente POST json = "{"; return readResponse(response); }
bool createMessgaeQueue(const char *tag, msgHandlerCB *cb) { bool result = true; if (init()) { MessageHeader *header = NewAndAddMessageHeader(tag, cb); if (NULL != header) { connectServer(header->fd, header->tag); printf("Begin to create Message Header Tag = %s\n", tag); } else { result = false; } } return result; }
int TVUClient::sendPackage(TVUPackage* package) { if(m_pChannel == NULL) { if(connectServer()<1) { //连接服务器 // if(connectServer()<1) // { flag = TVU_ERROR_SERVER_NOT_OPEN; return flag; // } } } return m_pChannel->sendTcpPackage(package); }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); this->connect(ui->connectButton, SIGNAL(clicked()), this, SLOT(connectServer())); this->connect(ui->startButton, SIGNAL(clicked()), this,SLOT(startTcpserver())); this->connect(ui->sendButton, SIGNAL(clicked()), this,SLOT(sendMessage())); ui->lineEdit->setEnabled(false); ui->sendButton->setEnabled(false); ui->textEdit->clear(); ui->textEdit->append("Initialized..."); isServer = 0; }
int8_t Adafruit_MQTT::connect() { // Connect to the server. if (!connectServer()) return -1; // Construct and send connect packet. uint8_t len = connectPacket(buffer); if (!sendPacket(buffer, len)) return -1; // Read connect response packet and verify it len = readPacket(buffer, 4, CONNECT_TIMEOUT_MS); if (len != 4) return -1; if ((buffer[0] != (MQTT_CTRL_CONNECTACK << 4)) || (buffer[1] != 2)) return -1; if (buffer[3] != 0) return buffer[3]; // Setup subscriptions once connected. for (uint8_t i=0; i<MAXSUBSCRIPTIONS; i++) { // Ignore subscriptions that aren't defined. if (subscriptions[i] == 0) continue; // Construct and send subscription packet. uint8_t len = subscribePacket(buffer, subscriptions[i]->topic, subscriptions[i]->qos); if (!sendPacket(buffer, len)) return -1; // Check for SUBACK if using MQTT 3.1.1 or higher // TODO: The Server is permitted to start sending PUBLISH packets matching the // Subscription before the Server sends the SUBACK Packet. // if(MQTT_PROTOCOL_LEVEL > 3) { // len = readPacket(buffer, 5, CONNECT_TIMEOUT_MS); // DEBUG_PRINT(F("SUBACK:\t")); // DEBUG_PRINTBUFFER(buffer, len); // if ((len != 5) || (buffer[0] != (MQTT_CTRL_SUBACK << 4))) { // return 6; // failure to subscribe // } // } } return 0; }
int CSocketClient::start(int nSocketType, const char* cszAddr, short nPort, int nStyle) { if ( AF_UNIX == nSocketType ) { setDomainSocketPath( cszAddr ); } else if ( AF_INET == nSocketType ) { if ( -1 == setInetSocket( cszAddr, nPort ) ) { _DBG( "set INET socket address & port fail" ); return -1; } } if ( -1 != createSocket( nSocketType, nStyle ) ) { if ( SOCK_STREAM == nStyle ) { if ( -1 == connectServer() ) { socketClose(); return -1; } } if ( -1 != externalEvent.m_nMsgId ) { if ( -1 == initMessage( externalEvent.m_nMsgId ) ) { throwException( "socket client create message id fail" ); } else { threadHandler->createThread( threadMessageReceive, this ); threadHandler->createThread( threadSocketRecvHandler, this ); } } _DBG( "[Socket Client] Socket connect success, FD:%d", getSocketfd() ); return getSocketfd(); } return -1; }