当前位置: 首页>>代码示例>>C++>>正文


C++ Tcp类代码示例

本文整理汇总了C++中Tcp的典型用法代码示例。如果您正苦于以下问题:C++ Tcp类的具体用法?C++ Tcp怎么用?C++ Tcp使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Tcp类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: findFreeTcp

Tcp* Tcp::findFreeTcp(struct espconn* pconn) {
	Tcp* cursor;
	for (cursor = _first; cursor != 0; cursor = cursor->_next)
		if ((cursor->isConnected() == false) && (cursor->getType() == LIVE))
			return cursor;
	return 0;
}
开发者ID:vortex314,项目名称:ea_actor,代码行数:7,代码来源:Tcp.cpp

示例2: listTcp

void Tcp::listTcp() {
	Tcp* cursor;
	char line[120];
	line[0] = 0;
	for (cursor = _first; cursor != 0; cursor = cursor->_next) {
		os_sprintf(line + strlen(line), "/ %X:%X %d %d", (uint32_t) cursor,
				cursor->_conn, cursor->getType(), cursor->isConnected());
	}
	LOGF(line);
}
开发者ID:vortex314,项目名称:ea_actor,代码行数:10,代码来源:Tcp.cpp

示例3: OnConnected

void Tcp::OnConnected(uv_connect_t *req, int status)
{
    Tcp *self = (Tcp *) req->data;
    if(self->m_pOutConnectHandler) {
        self->m_pOutConnectHandler->OnConnected(self, status);
    }

    if(status) {
        self->Close();
    }

    self->Unref();
}
开发者ID:LiTianjue,项目名称:uvpp,代码行数:13,代码来源:uv++-tcp.cpp

示例4: findTcp

void Tcp::sendCb(void *arg) {
	sends_cb++;
	struct espconn* pconn = (struct espconn*) arg;
	Tcp *pTcp = findTcp(pconn);
	if ( pTcp) {
		pTcp->_state = READY;
		pTcp->send();
//		pTcp->right().tell(pTcp->self(), REPLY(TXD), 0);
	} else {
		LOGF("Tcp not found");
	}
	return;
}
开发者ID:vortex314,项目名称:ea_actor,代码行数:13,代码来源:Tcp.cpp

示例5: Tcp

Tcp * Tcp::New(Loop &loop)
{
    Tcp *self = new Tcp();
    if(! self) {
        return NULL;
    }

    if(! self->Open(loop)) {
        return self;
    }

    delete self;

    return NULL;
}
开发者ID:LiTianjue,项目名称:uvpp,代码行数:15,代码来源:uv++-tcp.cpp

示例6: getLine

// get data from server to buffer line per line
int HTTPClient::getLine(Tcp c, uint8_t *buffer, size_t maxsize, int toRead) {
	unsigned int i;
	bool done = false;
	memset(buffer, 0, maxsize);  // set the buffer to 0

	for (i = 0; i < maxsize - 1 && !done; i++) {
		int bufchar = c.readchar();
		buffer[i] = (uint8_t) bufchar;

		if (buffer[i] == '\r') {
			i--;
		} else if (buffer[i] == '\n' || bufchar == -1) {  // if there is nothing more to read
			done = 1;
			buffer[i] = 0;
		}

		if (toRead == -1) {
			// do nothing: it'll stop only if the buffer is emptied
		} else if (toRead > 1) {
			toRead--;
		} else {
			done = true;
		}
	}
	if (toRead == 1) {
		return 1;
	} else {
		return i - 1;
	}
}
开发者ID:sapienzaapps,项目名称:galileo-terremoti,代码行数:31,代码来源:HTTPClient.cpp

示例7: findTcp

void Tcp::connectCb(void* arg) {
//	LOGF(" tcp connection received");

	struct espconn* pconn = (struct espconn*) arg;

	Tcp* pTcp = findTcp(pconn); // if found it's TcpClient

	if (pTcp == 0) {
		pTcp = findFreeTcp(pconn);
	}

	if (pTcp) {

		pTcp->loadEspconn(pconn);
		pTcp->registerCb(pconn);
		pTcp->_state = READY;

		/*		uint32_t keeplive;

		 espconn_set_opt(pesp_conn, ESPCONN_KEEPALIVE); // enable TCP keep alive

		 //set keepalive: 75s = 60 + 5*3
		 keeplive = 60;
		 espconn_set_keepalive(pesp_conn, ESPCONN_KEEPIDLE, &keeplive);
		 keeplive = 5;
		 espconn_set_keepalive(pesp_conn, ESPCONN_KEEPINTVL, &keeplive);
		 keeplive = 3; //try times
		 espconn_set_keepalive(pesp_conn, ESPCONN_KEEPCNT, &keeplive);  */
//		espconn_set_opt(pconn, ESPCONN_NODELAY);
//		espconn_set_opt(pconn, ESPCONN_COPY);
//		espconn_set_keepalive(pconn, ESPCONN_KEEPALIVE, (void*) 1);
//		espconn_set_keepalive(pconn, ESPCONN_KEEPIDLE, (void*) 1);
//		espconn_regist_time(pconn, 100, 0);
		pTcp->listener().tell(pTcp->self(), REPLY(CONNECT), 0);
		pTcp->_buffer.clear();
		pTcp->_txd.clear();
		pTcp->_connected = true;
		pTcp->_lastRxd = Sys::millis();
		pTcp->_state = READY;
	} else {
		LOGF(" no free TCP : disconnecting %X ", pconn);
		LOGF("  tcp :  %x  , ip : %d.%d.%d.%d:%d  ",
				pconn->reverse, pconn->proto.tcp->remote_ip[0], pconn->proto.tcp->remote_ip[1], pconn->proto.tcp->remote_ip[2], pconn->proto.tcp->remote_ip[3], pconn->proto.tcp->remote_port);
		espconn_disconnect(pconn);
	}
	return;
}
开发者ID:vortex314,项目名称:ea_stm32,代码行数:47,代码来源:Tcp.cpp

示例8: Handle

int Handle(const GwcHead &reqHead, const TReq &reqBody, GwcHead &rspHead, TResp &rspBody) {
	string ip = p.GetStr("ip", "127.0.0.1");
	uint16_t port = (uint16_t)p.GetU32("port", SERVER_PORT);
	uint32_t timeout = p.GetU32("timeout", 10000);
	string proto = p.GetStr("proto", "");

	char req[0x10000];
	uint32_t reqLen = sizeof(req);

	mtroe(code(reqHead, reqBody, req, reqLen), "");

	char rsp[0x10000];
	uint32_t rspLen = sizeof(rsp);

	in_addr addr = {inet_addr(ip.c_str())};
	printf(	"--------------------------------------------------------------------------------\n"
			"request host: address=%s:%u, timeout=%u\n"
			"request head: msgType=%u, version=%u, bodyLen=%lu\n"
			"request body: \n%s"
			"--------------------------------------------------------------------------------\n"
			, inet_ntoa(addr), port, timeout
			, reqHead.msgType, reqHead.version, reqLen - sizeof(reqHead)
			, reqBody.DebugString().c_str());

	if ("udp" == proto) {
		Udp udp;
		udp.SetTimeout(timeout);
		mtroe(udp.SendRecv(ip, port, req, reqLen, rsp, rspLen), "Udp::SendRecv failed, %s", udp.GetLastErr());
	} else {
		Tcp tcp;
		tcp.SetSendTimeout(timeout);
		tcp.SetTimeout(timeout);
		mtroe(tcp.SendRecv(ip, port, req, reqLen, rsp, rspLen), "Tcp::SendRecv failed, %s", tcp.GetLastErr());
	}

	mtroe(decode(rsp, rspLen, rspHead, rspBody), "");

	printf("--------------------------------------------------------------------------------\n"
			"response head: msgType=%u, version=%u, bodyLen=%lu\n"
			"response body: \n%s"
			"--------------------------------------------------------------------------------\n"
			, rspHead.msgType, rspHead.version, rspLen - sizeof(rspHead)
			, rspBody.DebugString().c_str());


	return 0;
}
开发者ID:jiabinruan,项目名称:gowithcool,代码行数:47,代码来源:my_tool.cpp

示例9: assert

int Tcp::Accept(/* [out] */ Stream **conn)
{
    assert(IsOpened());
    assert(conn && ! * conn);

    Tcp *newConn = New(GetLoop());
    if(! newConn) {
        return UV_ENOMEM;
    }

    int result = uv_accept(*this, *newConn);
    if(! result) {
        *conn = newConn;
    }
    else {
        newConn->Unref();
    }

    return result;
}
开发者ID:LiTianjue,项目名称:uvpp,代码行数:20,代码来源:uv++-tcp.cpp

示例10: main

int main(int argc, char **argv)
{
	DevInfo dev;
	Tcp tcp;
	Time time;
	Gpio gpio;
	//gpio.setDirection();

#if MAC_VERIFY
	if (!dev.verifyDeviceID()) //Mac Address 불일치
	{
		cout << "Not Matching MAC ADDRESS" << endl;
		exit(-1);
	}
#endif 
	std::thread * threads = new std::thread[MAX_POOL_SIZE];
	tcp.makeServerSocket(dev.getPort());
	tcp.bindSocket();
	tcp.listenSocket(MAX_POOL_SIZE);
	
	for (int i = 0; i < MAX_POOL_SIZE; i++)
	{
		threads[i] = thread(workerThread, dev, i);		 //TCP Multi Client Read / Write Thread
	}
	
	cp.make("/dev/ttyMAX2", 9600, 'E', 8, 1);				//CP 상태용 RS-485
	cp.setDebugMode(false);
	cp.setSlave(5);
	cp.connect();
	cp.setRS485Mode();
	
	power.make("/dev/ttyMAX3", 9600, 'N', 8, 1);		//전력용 RS-485
	power.setDebugMode(false);
	power.setSlave(1);
	power.connect();
	power.setRS485Mode();
	
	wiringPiSetup(); //GPIO lib setup
	
	for (int i = 0; i < MAX_POOL_SIZE; i++)
	{
		done[i] = false;
	}
	
	thread th(statusCP);  //CP상태요청 Thread
	
	cout << "[" << time.getCurrentTime() << "] " << "Staring Device Board Server " << endl;
	while (1)
	{
		tcp.acceptSocket();
		if (tcp.getClientSock())
		{ 
			if (tp.insertMultiMap(tcp.getClientSock(), tcp.getClientIP())) 
			{ 
				cout << "[" << time.getCurrentTime() << "] " <<  "Accept(" << tcp.getClientIP() << ")" << "::SEND SIGNAL(" << tp.getIndexNum() << ")" << endl;
				std::unique_lock<std::mutex> lock(mtx);
				lock.unlock();
				cond[tp.getIndexNum()].notify_one(); //Wait 된 Thread에게 Signal을 보냄
				usleep(1000);
				lock.lock();
			}
			else
			{
				tcp.closeClientSock(); 
			}	
		}
	}
	threads->join();
	th.join();
}
开发者ID:lingnice,项目名称:IncheonAirport,代码行数:70,代码来源:DeviceBoard.cpp

示例11: HTTPResponse

HTTPResponse *HTTPClient::httpRequest(HTTPMethod method, std::string URL,
									  std::map<std::string, std::string> postValues) {
	HTTPResponse *resp = new HTTPResponse();

	Tcp client;
	char serverName[100];
	unsigned short serverPort = 80;
	size_t pathOffset = hostFromURL(URL.c_str(), serverName, &serverPort);

	if (client.connectTo(std::string(serverName), serverPort)) {
		Log::d("Connect to server OK");
		char linebuf[1024];

		snprintf(linebuf, 1024, "%s %s HTTP/1.1", (method == HTTP_GET ? "GET" : "POST"), URL.c_str() + pathOffset);
		client.println(linebuf);

		if (serverPort != 80) {
			snprintf(linebuf, 1024, "Host: %s:%i", serverName, serverPort);
		} else {
			snprintf(linebuf, 1024, "Host: %s", serverName);
		}
		client.println(linebuf);

		client.println("Connection: close");

		if (method == HTTP_POST && postValues.empty()) {
			client.println("Content-Length: 0");
			client.println("");
		} else if (method == HTTP_POST && !postValues.empty()) {
			std::string reqBody;
			for (std::map<std::string, std::string>::iterator i = postValues.begin(); i != postValues.end(); ++i) {
				reqBody.append(i->first);
				reqBody.append("=");
				reqBody.append(i->second);
				reqBody.append("&");
			}
			reqBody = Utils::trim(reqBody, '&');
			client.println("Content-Type: application/x-www-form-urlencoded");

			unsigned long contentLength = reqBody.size();
			snprintf(linebuf, 1024, "Content-Length: %lu", contentLength);
			client.println(linebuf);

			client.println("");
			client.print(reqBody.c_str());

			Log::d("HTTP Post: %s", reqBody.c_str());
		}

		Log::d("HTTP Request to %s sent", URL.c_str());

		// Request sent, wait for reply
		unsigned long reqTime = Utils::millis();
		while (!client.available() && (Utils::millis() - reqTime < HTTP_RESPONSE_TIMEOUT_VALUE)) { ; }

		if (client.available()) {
			char rBuffer[300 + 1];
			memset(rBuffer, 0, 300 + 1);
			int s = getLine(client, (uint8_t *) rBuffer, 300);

			Log::d("buffer response[%i]: %s", s, rBuffer);

			if (strncmp(rBuffer, "HTTP/1.", 7) == 0) {
				resp->error = HTTP_OK;
				resp->responseCode = getResponseCode(rBuffer);

				// Read headers
				do {
					s = getLine(client, (uint8_t *) rBuffer, 300);
					if (s > 0 && strlen(rBuffer) != 0) {
						char *dppos = strchr(rBuffer, ':');
						*dppos = 0;
						if (*(dppos + 1) == ' ') {
							dppos++;
						}
						dppos++;
						resp->headers[std::string(rBuffer)] = std::string(dppos);
					}
				} while (s > 0 && strlen(rBuffer) != 0);

				resp->body = NULL;
				if (resp->headers.count("Content-Length") == 1) {
					size_t bodySize = (size_t) atol(resp->headers["Content-Length"].c_str());
					resp->body = (uint8_t *) malloc(bodySize + 1);
					memset(resp->body, 0, bodySize + 1);
					client.readall(resp->body, bodySize);
				}
			} else {
				Log::e("HTTP malformed reply");
				resp->error = HTTP_MALFORMED_REPLY;
			}
		} else {
			Log::e("HTTP request timeout");
			resp->error = HTTP_REQUEST_TIMEOUT;
		}
	} else {
		Log::e("HTTP connection timeout");
		resp->error = HTTP_CONNECTION_TIMEOUT;
	}
	Log::d("Stopping tcp client");
//.........这里部分代码省略.........
开发者ID:sapienzaapps,项目名称:galileo-terremoti,代码行数:101,代码来源:HTTPClient.cpp

示例12: fopen

HTTPResponse *HTTPClient::httpPostFile(std::string URL, std::string file) {
	ssize_t fileSize = Utils::fileSize(file.c_str());
	if (fileSize == -1) return NULL;

	FILE *fp = fopen(file.c_str(), "r");
	if (fp == NULL) {
		// Woops!
		return NULL;
	}
	uint8_t *buf = (uint8_t *) malloc(fileSize);
	memset(buf, 0, (size_t) fileSize);
	fread(buf, fileSize, 1, fp);
	fclose(fp);

	HTTPResponse *resp = new HTTPResponse();

	Tcp client;
	char serverName[100];
	unsigned short serverPort = 80;
	size_t pathOffset = hostFromURL(URL.c_str(), serverName, &serverPort);

	if (client.connectTo(std::string(serverName), serverPort)) {
		Log::d("Connect to server OK");
		char linebuf[1024];

		snprintf(linebuf, 1024, "POST %s HTTP/1.1", URL.c_str() + pathOffset);
		client.println(linebuf);

		if (serverPort != 80) {
			snprintf(linebuf, 1024, "Host: %s:%i", serverName, serverPort);
		} else {
			snprintf(linebuf, 1024, "Host: %s", serverName);
		}
		client.println(linebuf);

		client.println("Content-Type: application/octet-stream");
		client.println("Connection: close");

		std::string contentLength = "Content-Length: " + Utils::toString((int) fileSize);
		client.println(contentLength.c_str());
		client.println("");

		client.send(buf, fileSize);

		Log::d("HTTP Request to %s sent", URL.c_str());

		// Request sent, wait for reply
		unsigned long reqTime = Utils::millis();
		while (!client.available() && (Utils::millis() - reqTime < HTTP_RESPONSE_TIMEOUT_VALUE)) {
#ifndef NOWATCHDOG
			Watchdog::heartBeat();
#endif
		}

		if (client.available()) {
			char rBuffer[300 + 1];
			memset(rBuffer, 0, 300 + 1);
			int s = getLine(client, (uint8_t *) rBuffer, 300);

			Log::d("buffer response[%i]: %s", s, rBuffer);

			if (strncmp(rBuffer, "HTTP/1.", 7) == 0) {
				resp->error = HTTP_OK;
				resp->responseCode = getResponseCode(rBuffer);

				// Read headers
				do {
					s = getLine(client, (uint8_t *) rBuffer, 300);
					if (s > 0 && strlen(rBuffer) != 0) {
						char *dppos = strchr(rBuffer, ':');
						*dppos = 0;
						if (*(dppos + 1) == ' ') {
							dppos++;
						}
						dppos++;
						resp->headers[std::string(rBuffer)] = std::string(dppos);
					}
				} while (s > 0 && strlen(rBuffer) != 0);

				resp->body = NULL;
				if (resp->headers.count("Content-Length") == 1) {
					size_t bodySize = (size_t) atol(resp->headers["Content-Length"].c_str());
					resp->body = (uint8_t *) malloc(bodySize + 1);
					memset(resp->body, 0, bodySize + 1);
					client.readall(resp->body, bodySize);
				}
			} else {
				Log::e("HTTP malformed reply");
				resp->error = HTTP_MALFORMED_REPLY;
			}
		} else {
			Log::e("HTTP request timeout");
			resp->error = HTTP_REQUEST_TIMEOUT;
		}
	} else {
		Log::e("HTTP connection timeout");
		resp->error = HTTP_CONNECTION_TIMEOUT;
	}
	free(buf);
	Log::d("Stopping tcp client");
//.........这里部分代码省略.........
开发者ID:sapienzaapps,项目名称:galileo-terremoti,代码行数:101,代码来源:HTTPClient.cpp

示例13: main

int main()

{
    {
        MyTimeoutHandler timeoutHandler;

        SignalHandler signalHandler;
        Signal *signal = Signal::New();
        timeoutHandler.AddHandle(signal);
        assert(! signal->Start(SIGINT, signalHandler));
        signal->Unref();

        signal = Signal::New();
        timeoutHandler.AddHandle(signal);
        assert(! signal->Start(SIGTERM, signalHandler));
        signal->Unref();

        Server serverEventHandler(timeoutHandler);
        Tcp *server = Tcp::New();
        timeoutHandler.AddHandle(server);
        assert(! server->Bind(Ip4Address("0.0.0.0", 1234)));
        assert(! server->Listen(serverEventHandler));
        server->Unref();

        Client clientEventHandler;
        Tcp *client = Tcp::New();
        timeoutHandler.AddHandle(client);
        assert(! client->Connect(Ip4Address("127.0.0.1", 1234), &clientEventHandler));
        client->Unref();

        PingPeer peer1("Peer1");
        Udp *endPoint1 = Udp::New();
        assert(endPoint1);
        timeoutHandler.AddHandle(endPoint1);
        assert(! endPoint1->Bind(Ip4Address("0.0.0.0", 1357)));
        assert(! endPoint1->RecvStart(peer1));

        PingPeer peer2("Peer2");
        Udp *endPoint2 = Udp::New();
        assert(endPoint2);
        timeoutHandler.AddHandle(endPoint2);
        assert(! endPoint2->Bind(Ip4Address("0.0.0.0", 2468)));
        assert(! endPoint2->RecvStart(peer2));

        Buffer *buf = new Buffer("Hello");
        assert(! endPoint1->Send(*buf, Ip4Address("127.0.0.1", 2468)));
        buf->Unref();

        buf = new Buffer("World");
        assert(! endPoint2->Send(*buf, Ip4Address("127.0.0.1", 1357)));
        buf->Unref();

        endPoint1->Unref();
        endPoint2->Unref();

        Timer *timer = Timer::New();
        timeoutHandler.AddHandle(timer);
        assert(timer);
        assert(! timer->Start(1000, timeoutHandler));
        timer->Unref();

        Loop::Run();
        timeoutHandler.CloseHandles();
        Loop::Free();
    }

    cout << Handle::count << " handle alive" << endl;

    return 0;
}
开发者ID:LiTianjue,项目名称:uvpp,代码行数:70,代码来源:test.cpp

示例14: main

int main(int argc, char *argv[] )
{

    if ( testBytes()!=true) exit(1);
    logger.module("Main");
    logger.level(Logger::INFO)<<"Start "<<argv[0]<<" version : "<<__DATE__ << " " << __TIME__ ;
    logger.flush();

    loadOptions(argc,argv);
    interceptAllSignals();

    usb.setDevice(context.device);
    usb.setBaudrate(context.baudrate);
    tcp.setHost(context.host);
    tcp.setPort(context.port);

    UsbConnection usbConnection(&usb);
    Gateway gtw(&usb,&tcp);
    uint64_t sleepTill=Sys::upTime()+TIMER_TICK;
    MsgQueue::publish(os,SIG_INIT);
    Msg msg;
    while(true)
    {
        poller(usb.fd(),tcp.fd(),sleepTill);
        sleepTill = Sys::upTime()+TIMER_TICK; // was 100000
        while (MsgQueue::get(msg))
        {
            logMsg(msg);
            Handler::dispatchToChilds(msg);
        }
    }
}
开发者ID:vortex314,项目名称:projects,代码行数:32,代码来源:main.cpp

示例15: dispatch

    bool dispatch(Msg& msg)
    {
        PT_BEGIN (  );
        while(true)
        {
            PT_YIELD_UNTIL( msg.is(_tcp,SIG_RXD) || msg.is(_usb,SIG_RXD) );
            if ( msg.is(_tcp,SIG_RXD))
            {
                MqttIn* mqttIn = (MqttIn*)msg.data;
                Str str(256);
                str << "MQTT TCP->USB:";
                mqttIn->toString(str);
                logger.info()<< str;
                logger.flush();
                usb.send(*mqttIn->getBytes());
            }
            else if ( msg.is(_usb,SIG_RXD))
            {
                MqttIn* mqttIn = (MqttIn*)msg.data;
                Str str(256);
                str << "MQTT USB->TCP:";
                mqttIn->toString(str);
                logger.info()<< str;
                logger.flush();

                if ( _tcp->isConnected() )
                {
                    if ( mqttIn->type() == MQTT_MSG_CONNECT ) // simulate a reply
                    {
                        MqttOut m(10);
                        m.ConnAck(0);
                        //                           uint8_t CONNACK[]={0x20,0x02,0x00,0x00};
                        logger.info()<< "CONNACK virtual,already tcp connected";
                        logger.flush();
                        usb.send(m);
                    }
                    else
                    {
                        tcp.send(*mqttIn->getBytes());
                    }
                }
                else
                {
                    if ( mqttIn->type() == MQTT_MSG_CONNECT )
                    {
                        tcp.connect();
                        tcp.send(*mqttIn->getBytes());
                    }
                    else
                    {
                        logger.info()<< "dropped packet, not connected.";
                        logger.flush();
                        usb.disconnect();
                    }
                }
            }
        }
        PT_END (  );
    }
开发者ID:vortex314,项目名称:projects,代码行数:59,代码来源:main.cpp


注:本文中的Tcp类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。