void TCPClient::AfterRecv(uv_stream_t* handle, ssize_t nread, const uv_buf_t* buf) { TcpClientCtx* theclass = (TcpClientCtx*)handle->data; assert(theclass); TCPClient* parent = (TCPClient*)theclass->parent_server; if (nread < 0) { if (parent->reconnectcb_) { parent->reconnectcb_(NET_EVENT_TYPE_DISCONNECT, parent->reconnect_userdata_); } if (!parent->StartReconnect()) { fprintf(stdout, "Start Reconnect Failure.\n"); return; } if (nread == UV_EOF) { fprintf(stdout, "Server close(EOF), Client %p\n", handle); LOG(INFO) << ("Server close(EOF)"); } else if (nread == UV_ECONNRESET) { fprintf(stdout, "Server close(conn reset),Client %p\n", handle); LOG(INFO) << ("Server close(conn reset)"); } else { fprintf(stdout, "Server close,Client %p:%s\n", handle, GetUVError(nread).c_str()); LOG(INFO) << "Server close" << GetUVError(nread); } uv_close((uv_handle_t*)handle, AfterClientClose);//close before reconnect return; } parent->send_inl(NULL); if (nread > 0) { theclass->packet_->recvdata((const unsigned char*)buf->base, nread); } }
void loop() { if (nextTime > millis()) return; g_connected = client.connect(host, g_port); if (!g_connected) { client.stop(); // If TCP Client can't connect to host, exit here. return; } g_https_complete = false; g_bytes_received = 0; if (g_https_trace) { freemem = System.freeMemory(); Serial.print("free memory: "); Serial.println(freemem); } int32 rc; if ((rc = httpsClientConnection(httpRequestContent, 0, NULL) < 0)) { // TODO: When massive FAIL httpsclientCleanUp(); digitalWrite(anomalyLed, HIGH); delay(500); digitalWrite(anomalyLed, LOW); delay(500); digitalWrite(anomalyLed, HIGH); delay(500); digitalWrite(anomalyLed, LOW); } else { digitalWrite(heartbeatLed, HIGH); delay(250); digitalWrite(heartbeatLed, LOW); } client.stop(); nextTime = millis() + 5000; }
void loop() { delay(1); if (!WiFi.ready()) { Particle.process(); WiFi.connect(); while(WiFi.connecting()) {Particle.process();} }// if (!WiFi.ready()) else { complete = false; lastTime = millis(); while ((!complete) && (millis() - lastTime < 10000)){ if (client.connect( server, serverPort)) { if (client.connected()) { out(clientmsg); lastTime = millis(); while ((!client.available()) && (millis() - lastTime < 10000)) {Particle.process();}//wait for response in(inmsg,10);//10 pure trial and error myInStr =inmsg; if (myInStr.indexOf(replymsg) >= 0) { digitalWrite(D7, 1); // Flashes the LED lastTime = millis(); while ( millis()-lastTime < 5) { } //5 digitalWrite(D7, 0); // Flashes the LED complete = true; }//if (myInStr.indexOf(replymsg) >= 0) }//if (client.connected()) }//if (client.connect( server, serverPort)) }//while (!complete) }//else }//loop
void loop() { char tmp[3]; int charPosition = 0; // While there is data in the buffer, lets read it. while(client.available()) { char c = client.read(); // Check if we reached the end of the data if(c == ',') { // use the accumulated value pData(tmp); // Reset tmp[0]; charPosition = 0; } else { // Save char in to the temp array tmp[charPosition] = c; // Increment the position of the array charPosition++; } } }
INT_PTR WINAPI DlgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_INITDIALOG: ShowWindow(hWnd, SW_SHOW); while (!_client.ConnectServer("92.241.225.221", 1000)) Sleep(1000); break; case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_BUTTON2: { char* data = new char[256]; for (int i = 0; i < 256; i++) data[i] = '\0'; GetDlgItemText(hWnd, IDC_EDIT1, data, 256); _client.SendData(data, strlen(data)); break; } } break; case WM_CLOSE: EndDialog(hWnd,0); break; default: return false; } return true; }
void TCPClient::AfterConnect(uv_connect_t* handle, int status) { TcpClientCtx* theclass = (TcpClientCtx*)handle->handle->data; TCPClient* parent = (TCPClient*)theclass->parent_server; if (status) { parent->connectstatus_ = CONNECT_ERROR; parent->errmsg_ = GetUVError(status); LOG(ERROR)<<"client(" << parent << ") connect error:" << parent->errmsg_; fprintf(stdout, "connect error:%s\n", parent->errmsg_.c_str()); if (parent->isreconnecting_) {//reconnect failure, restart timer to trigger reconnect. uv_timer_stop(&parent->reconnect_timer_); parent->repeat_time_ *= 2; uv_timer_start(&parent->reconnect_timer_, TCPClient::ReconnectTimer, parent->repeat_time_, parent->repeat_time_); } return; } int iret = uv_read_start(handle->handle, AllocBufferForRecv, AfterRecv); if (iret) { parent->errmsg_ = GetUVError(status); LOG(ERROR)<<"client(" << parent << ") uv_read_start error:" << parent->errmsg_; fprintf(stdout, "uv_read_start error:%s\n", parent->errmsg_.c_str()); parent->connectstatus_ = CONNECT_ERROR; } else { parent->connectstatus_ = CONNECT_FINISH; LOG(INFO) << "client(" << parent << ")run"; } if (parent->isreconnecting_) { fprintf(stdout, "reconnect succeed\n"); parent->StopReconnect();//reconnect succeed. if (parent->reconnectcb_) { parent->reconnectcb_(NET_EVENT_TYPE_RECONNECT, parent->reconnect_userdata_); } } }
void loop() { if (client.connected()) { while (client.available()) { in(inmsg,1000); myInStr =inmsg; if (myInStr.indexOf(clientmsg) >= 0) { digitalWrite(D7, 1); delay(50); digitalWrite(D7, 0); sprintf(outmsg,"%c",replymsg); out(outmsg); //THIS WORKS TOO // IPAddress myIP = WiFi.localIP(); // sprintf(outmsg, "%d.%d.%d.%d,%d,2,%d,3,4/e", myIP[0], myIP[1], myIP[2], myIP[3],counter,simulate_temp); // out(outmsg); //but don't yet have a tcpclient that can handle such a response }//if (myInStr.indexOf("7") >= 0) }//while (client.available()) }//if (client.connected()) client.read(); client.flush(); // client.stop(); //apparently unnecessary client = server.available(); //keep connection alive long enough for client to receive reply lastTime = millis(); while ( millis()-lastTime < 300) {} }//loop
void TCPClient::RecvThread(void* p) { TCPClient* pSelf = reinterpret_cast<TCPClient*>(p); if (NULL != pSelf) { pSelf->DoRecv(); } }
void TCPClient::ReconnectThrd(void* p) { TCPClient* pSelf = reinterpret_cast<TCPClient*>(p); if (NULL != pSelf) { pSelf->DoReconnect(); } }
void TCPClient::GetPacket(const NetPacket& packethead, const unsigned char* packetdata, void* userdata) { assert(userdata); TcpClientCtx* theclass = (TcpClientCtx*)userdata; TCPClient* parent = (TCPClient*)theclass->parent_server; if (parent->recvcb_) {//cb the data to user parent->recvcb_(packethead, packetdata, parent->recvcb_userdata_); } }
int tcpLog(String message) { if (tcp.connected()) { tcp.print(STX + Spark.deviceID() + ETX + message + EOT); delay(250); // try not to flood socket with too many writes return 1; } else { return -1; } }
// // TCP stuff // void sendToGraphite( String id, String value ) { TCPClient client; if ( client.connect( "rpi2", 2003 ) ) { client.println( id + " " + value + " " + String( Time.now() ) ); client.stop(); } }
void loop() { if (client.connected()) { Firmata.sendString("Hello World!"); delay(1000); } else { Serial.println("Disconnected."); client.stop(); while(1) {}; // loop forever } }
void TCPClient::AsyncCB(uv_async_t* handle) { TCPClient* theclass = (TCPClient*)handle->data; if (theclass->isuseraskforclosed_) { theclass->closeinl(); return; } //check data to send theclass->send_inl(NULL); }
void loop() { if (clientWww.connected()) { int position = 0; int canI = 0; // echo all available bytes back to the client while (clientWww.available()) { char c = clientWww.read(); char url[200]; // Detect space if(c == 32) { canI = !canI; } // Save only data in between spaces if(canI) { // Discard spaces if(c != 32) { url[position++] = c; } } // Detect end of the line if(c == 10) { // Null terminate our array url[position + 1] = 0; response(url); // Discard the rest of the header clientWww.flush(); } } } else { // if no client is yet connected, check for a new connection clientWww = serverWww.available(); } }
int sendRequest (byte* host, unsigned short port, char* response, unsigned short responseSize, boolean keepAlive) { if (myClient.connected() || myClient.connect(host, port)) { uint32_t startTime = millis(); myClient.write((const uint8_t *)mainbuffer, strlen(mainbuffer)); myClient.flush(); while(!myClient.available() && (millis() - startTime) < 5000){ SPARK_WLAN_Loop(); }; while(myClient.available()) { readbytes = myClient.read((uint8_t*) response, responseSize); if (readbytes == -1) break; } myClient.flush(); if(!keepAlive) { myClient.stop(); } } else { // unable to connect return 1; } return 0; }
int main() { signal(SIGPIPE, SIG_IGN); char buf[BUFSIZ]; int clientCount = 0; try { TCPServer server(8001); int listenfd = server.getfd(); Epoll epoll; // 将监听套接字注册到epoll epoll.addfd(server.getfd(), EPOLLIN, true); while (true) { int nReady = epoll.wait(); for (int i = 0; i < nReady; ++i) // 如果是监听套接字发生了可读事件 if (epoll.getEventOccurfd(i) == listenfd) { int connectfd = accept(listenfd, NULL, NULL); if (connectfd == -1) err_exit("accept error"); cout << "accept success..." << endl; cout << "clientCount = " << ++ clientCount << endl; setUnBlock(connectfd, true); epoll.addfd(connectfd, EPOLLIN, true); } else if (epoll.getEvents(i) & EPOLLIN) { TCPClient *client = new TCPClient(epoll.getEventOccurfd(i)); memset(buf, 0, sizeof(buf)); if (client->read(buf, sizeof(buf)) == 0) { cerr << "client connect closed..." << endl; // 将该套接字从epoll中移除 epoll.delfd(client->getfd()); delete client; continue; } cout << buf; client->write(buf); } } } catch (const SocketException &e) { cerr << e.what() << endl; err_exit("TCPServer error"); } catch (const EpollException &e) { cerr << e.what() << endl; err_exit("Epoll error"); } }
void loop() { unsigned int t = millis(); if (nextTime > t) return; StaticJsonBuffer<GF_JSON_SIZE> glowfishJson; JsonObject& top = glowfishJson.createObject(); top["device_id"] = (const char *) System.deviceID(); JsonObject& data_set = top.createNestedObject("data_set"); // TODO: I don't quite understand how much memory needs to get allocated //JsonObject& time = top.createNestedArray("time"); JsonArray& freememJ = data_set.createNestedArray("freemem"); freememJ.add(System.freeMemory()); JsonArray& timeup = data_set.createNestedArray("timeup"); timeup.add(t/1000); char jsonBuf[GF_JSON_SIZE]; size_t bufsize = top.printTo(jsonBuf, sizeof(jsonBuf)); g_connected = client.connect(host, g_port); if (!g_connected) { client.stop(); // If TCP Client can't connect to host, exit here. return; } g_https_complete = false; g_bytes_received = 0; if (g_https_trace) { Serial.print("free memory: "); Serial.println(freemem); } int rc; httpsclientSetPath(se_endpoint); if ((rc = httpsClientConnection(httpRequestContent, bufsize, jsonBuf,received_msg)) < 0) { // TODO: When massive FAIL if (g_https_trace) { Serial.print("httpsClientConnection Returned "); Serial.println(rc); } httpsclientCleanUp(); // Blink an LED twice to indicate trouble digitalWrite(anomalyLed, HIGH); delay(500); digitalWrite(anomalyLed, LOW); delay(500); digitalWrite(anomalyLed, HIGH); delay(500); digitalWrite(anomalyLed, LOW); return; } else { // Blink an LED once to indicate success digitalWrite(heartbeatLed, HIGH); delay(250); digitalWrite(heartbeatLed, LOW); } client.stop(); nextTime = millis() + 5000; }
void in(char *ptr, uint8_t timeout) { int pos = 0; unsigned long lastdata = millis(); while ( client.available() || (millis()-lastdata < timeout)) { if (client.available()) { char c = client.read(); lastdata = millis(); ptr[pos] = c; pos++; }//if (client.available()) }//while ( client.available() || (millis()-lastdata < timeout)) client.read(); }//void in(char *ptr, uint8_t timeout)
void loop() { if (client.connected()) { if (client.available()) { char pin = client.read() - '0' + D0; char level = client.read(); if ('h' == level) { digitalWrite(pin, HIGH); } else { digitalWrite(pin, LOW); } } } }
void * receiver(void * v) { TCPClient *client = (TCPClient*) v; assert(client != NULL); assert (client->get_sock() >= 0); while (client->running) { if (!client->running) { break; } char buffer[RECEIVE_BUFFER_SIZE]; int allBytesRead = 0; int actBytesRead = 0; read_modes act_read_mode = client->get_read_mode(); while (allBytesRead < (RECEIVE_BUFFER_SIZE-1)) { actBytesRead = recv(client->get_sock(), buffer, sizeof(buffer), 0); if (actBytesRead < 0) { // perror("receive failed!"); break; } else if (actBytesRead == 0) { std::cout << "connection reset.. " << std::endl; if (allBytesRead > 0) { buffer[allBytesRead+1] = '\0'; std::cout << "last bytes received: " << buffer << std::endl; } client->close_conn(); client->running = false; return 0; } allBytesRead += actBytesRead; if (act_read_mode == INCOME) { break; } } if (allBytesRead > 0) { buffer[allBytesRead] = '\0'; std::cout << "received: " << buffer << std::endl; } } return 0; }
void HistogramUpdater::reloadIni() { try { stringstream serveradress; serveradress << _server << ":" << _port; TCPClient client (serveradress.str()); client.reloadIni(); } catch (const runtime_error &error) { cout << "HistogramUpdater::reloadIni(): "<<error.what()<<endl; } }
void TCPClient::AfterSend(uv_write_t* req, int status) { TCPClient* theclass = (TCPClient*)req->data; if (status < 0) { if (theclass->writeparam_list_.size() > MAXLISTSIZE) { FreeWriteParam((write_param*)req); } else { theclass->writeparam_list_.push_back((write_param*)req); } LOG(ERROR)<<"send error:" << GetUVError(status); fprintf(stderr, "send error %s\n", GetUVError(status).c_str()); return; } theclass->send_inl(req); }
int main(int argc, char* argv[]) { // define Arguments and Application variables define_args(); // parse Arguments if (A.parseArgs(argc, argv) == false) { A.printArgs(); exit(EXIT_FAILURE); } // print Help if (A.getParam<bool>("p_help") == true) { A.printArgs(); exit(EXIT_SUCCESS); } TCPClient* client = new TCPClient(); TCPSocket* socket = client->connect(A.getParam<const char*>("p_server"), A.getParam<int>("p_port")); if (socket != NULL) { // build message std::string message(A.getArg(0)); for (size_t i = 1; i < A.numArg(); i++) { message += " "; message += A.getArg(i); } socket->send(message.c_str(), message.size()); char data[1024]; size_t datalen; datalen = socket->recv(data, sizeof(data)-1); data[datalen] = '\0'; std::cout << data; delete socket; } delete client; return 0; }
void response(char* url) { // default page is the error page const char* page = error; // Get the length of our URL and remove the null termination int urlLen = strlen(url) - 1; // HOME: check only for the length of the URL, since the home page // is represented by a forward slash / if(urlLen == 1) { page = home; } // MORE: look for the word if(memcmp(url, "/more", 5) == 0) { page = more; } // HOME: look for the word if(memcmp(url, "/author", 6) == 0) { page = author; } // Inform the browser that everything is ok clientWww.write("HTTP/1.1 200 OK\n\r"); // Tell the encoding that we are using clientWww.write("Content-Type: text/html; charset=ascii\n\r"); // Separate the header from the body with one empty line clientWww.write("\n\r"); // Send our content clientWww.write(page); // Close the connection clientWww.stop(); }
void ReadCB(const NetPacket& packet, const unsigned char* buf, void* userdata) { char senddata[256] = {0}; TCPClient* client = (TCPClient*)userdata; sprintf(senddata, "****recv server data(%p,%d)", client, packet.datalen); fprintf(stdout, "%s\n", senddata); NetPacket tmppack = packet; tmppack.datalen = (std::min)(strlen(senddata), sizeof(senddata) - 1); std::string retstr = PacketData(tmppack, (const unsigned char*)senddata); if (client->Send(&retstr[0], retstr.length()) <= 0) { fprintf(stdout, "(%p)send error.%s\n", client, client->GetLastErrMsg()); } fprintf(stdout, "call time %d\n", ++call_time); //if (call_time > 50) { // is_exist = true; //} }
void tcpKeepAlive() { unsigned long now = millis(); if (tcp.connected()) { if (now > kaTimer) { tcp.flush(); tcpLog("ENQ"); // For logger view tcp.print(ENQ); // Heartbeat signal kaWait = now + 500; kaWaiting = true; tcpKeepAliveReset(); } if (kaWaiting && (kaWait > now)) { if (tcp.available()) { char read = tcp.read(); if (read == ACK) { // tcpLog("ACK"); kaWaiting = false; } } } else if (kaWaiting && kaWait < now) { tcpLog("Timed out"); kaWaiting = false; tcp.flush(); tcp.stop(); } } }
void loop() { //low power WiFi.disconnect(); System.sleep(D3, RISING, 4); if (digitalRead(D3)) {digitalWrite(D6,HIGH);delay(200);digitalWrite(D6,LOW);} while (!WiFi.ready()) { Particle.process(); WiFi.connect(); while(WiFi.connecting()){Particle.process();} }// while (!WiFi.ready()) complete = false; //don't unsuccessfully persist beyond 10 secs, just go back to sleep lastTime = millis(); while ((!complete) && (millis() - lastTime < 10000)){ if (client.connect( server, serverPort)) { if (client.connected()) { sprintf(outmsg,"%c",clientmsg); out(outmsg); lastTime = millis(); while ((!client.available()) && (millis() - lastTime < 5000)) { } lastTime = millis(); while ((millis() - lastTime < 300)) {}//plays better with nodejs server? //now get confirmation from server that server received msg while (client.available()) { read_char = client.read(); if(read_char == replymsg ) { //we got confirmation digitalWrite(D7,HIGH);delay(10);digitalWrite(D7,LOW); client.read(); complete = true; }//if(read_char == replymsg ) }//while (client.available()) }//if (client.connected()) }//if (client.connect( server, serverPort)) client.read(); client.flush(); // client.stop();//apparently unnecessary }//while (!complete) // prevent nodejs ECONNRESET, not necessay with another photon?? lastTime = millis(); while ((millis() - lastTime < 500)) {}//prevent nodejs ECONNRESET delay(1); }//loop
int tcpConnect(String ip) { byte address[4]; ipArrayFromString(address, ip); if (tcp.connect(address, tcpPort)) { tcpKeepAliveReset(); return 1; } else { return -1; } }
int connectToMyServer(String ip) { byte serverAddress[4]; ipArrayFromString(serverAddress, ip); if (client.connect(serverAddress, 9000)) { return 1; // successfully connected } else { return -1; // failed to connect } }