Esempio n. 1
0
bool TcpServer::processAccept(int efd)
{
    if (this->stopping) return false;

    int socket;
    while (true)
    {
        ISocket *sock = this->listenSocket->accept();
        if (sock == 0)
        {
            if (errno == EAGAIN)
            {
                return true;
            }
            else
            {
                LOG("error while accepting. returned " << errno);
                return false;
            }
        }
        socket = sock->getSocket();
        int flags = fcntl(socket,F_GETFL,0);
        fcntl(socket, F_SETFL, flags | O_NONBLOCK);
        TcpClient* client = this->clientFactory->create(sock);
        clientList[socket] = client;
        client->setControlEventFd(this->controlEventFd);
        client->onConnected();
        addFdToEpoll(efd,socket);
    }

    return true;
}
Esempio n. 2
0
int main(int argc, char** argv) {
	const std::string& endpoint = (const std::string&)argv[1];

	pid_t pid = fork();
    if (pid == 0) {
		pid_t pid2 = fork();
	    if (pid2 == 0) {
	    	UdpClient *client = new UdpClient(1);
			client->Execute(endpoint);
	    } else {
	    	TcpClient *client = new TcpClient(2);
	        client->Execute(endpoint);
	    }
    } else {
		pid_t pid3 = fork();
	    if (pid3 == 0) {
        	UdpClient *client = new UdpClient(3);
    		client->Execute(endpoint);
        } else {
        	TcpClient *client = new TcpClient(4);
            client->Execute(endpoint);
        }
    }
	return 0;
}
void ClientTCP()
{
    TcpClient client;
    Packet data;
    data.SetByteOrder(CX_PACKET_BIG_ENDIAN);
    if(!client.InitializeSocket(HOSTNAME, PORT)) 
    {
        cout << "Unable to connect to host " << HOSTNAME << endl;
        return;
    }
    cout << "Initialized TCP Client Socket\n";
    char key = 0;
    while(key != 27) 
    {

        if((key = GetChar()) > 0) 
        {
            data.Clear();       //  Clear packet and encode data.
            data.Write(key);
            client.Send(data);  //  Send data (could send character array also if desired
            /* Alternative way to send:
               client.Send(&key, 1);    //  Send buffer/array.
            */
            data.Clear();
            if(client.Recv(data, 50, 0))
            {
                cout << *data.Ptr() << endl;
            }
            //cout << key;
        }
    }
}
Esempio n. 4
0
void LocalPC::tcpServerReceiveData(void *tcp, char *buffer, int size)
{
    DEBUG_OUTPUT("[LocalPC]receive:\n%s\n", buffer_format(buffer, size));
    HeartbeatProtocol protocol;
    Heartbeat *hb = protocol.find(buffer, size);
    if(hb!=NULL)
    {
        delete hb;

        char *p = NULL;
        int size = 0;
        bool slave = isSlave();
        double timePoint = getSetupTime();
        Heartbeat *t = protocol.makeHeartbeat(slave, timePoint);
        if(NULL!=t)
        {
            if(t->makeBuffer(&p, size))
            {
                TcpClient *client = (TcpClient *)tcp;
                client->send(p, size);
                delete p;
            }
        }
    }
}
Esempio n. 5
0
int main(int argc, char** argv)
{

  const unsigned int IP_ARG_IDX = 1;
  TcpClient connection;
  ros::init(argc, argv, "state_interface");

  if (argc != 1) //Only one argument, the robot IP address is accepted
  {
    ROS_INFO("Robot state connecting to IP address: %s", argv[IP_ARG_IDX]);
    connection.init(argv[IP_ARG_IDX], StandardSocketPorts::STATE);

    std::vector<std::string> joint_names;
    joint_names.push_back("joint_s");
    joint_names.push_back("joint_l");
    joint_names.push_back("joint_e");
    joint_names.push_back("joint_u");
    joint_names.push_back("joint_r");
    joint_names.push_back("joint_b");
    joint_names.push_back("joint_t");

    RobotStateInterface rsi;
    if (rsi.init(&connection, joint_names))
    {
      rsi.run();
    }

  }
  else
  {
    ROS_ERROR("Missing command line arguments, usage: robot_state <robot ip address>");
  }

  return 0;
}
Esempio n. 6
0
int main(int argc, char** argv) {
	net_prepare();

	// Connect the AR.Drone video port
	TcpClient* videoClient = new  TcpClient(ARDRONE_IP, VIDEO_PORT);
	if (!videoClient->is_valid()) {
		cerr << "can't connnected to the video tcp..." << endl;
		abort();
	}

	int count = 0; // control the size of frames
	std::ofstream videoIO("video.h264", ios::binary);

	const int max_buf_size = VideoEncap::TcpPackSize;
	char* buf = (char*)malloc(max_buf_size);
	VideoEncap encap;
	while (true) {
		if (count>1500) {
			break;
		}
		
		videoClient->recv(buf, max_buf_size, NULL);
		videoIO.write((char*)buf, max_buf_size);
		//vardump_hex(buf, max_buf_size); // output the data (hex format)
		//if (encap.process(buf)) {
		//	videoIO.write((char*)encap.get_data(), encap.get_data_size());
		//	count++;
			//vardump_hex(encap.get_data(), encap.get_data_size());
		//}
		count++;
	}
	videoIO.close();
	net_end();
	return 0;
}
Esempio n. 7
0
// Message passing routine, used to send and receive a typed message
// Useful for checking the packing and unpacking of message data.
void fakeMessagePassing(TypedMessage &send, TypedMessage &recv)
{
  const int tcpPort = TEST_PORT_BASE+401;
  char ipAddr[] = "127.0.0.1";

  TcpClient tcpClient;
  TcpServer tcpServer;
  SimpleMessage msgSend, msgRecv;

  send.toTopic(msgSend);

  // Construct server

  tcpServer.init(tcpPort);

  // Construct a client
  tcpClient.init(&ipAddr[0], tcpPort);
  tcpClient.makeConnect();  // make tcp client connection

  tcpServer.makeConnect();      // make tcp server connection

  tcpClient.sendMsg(msgSend);   // send message
  tcpServer.receiveMsg(msgRecv); // physically receive message
  recv.init(msgRecv); // copy received message into reference
}
Esempio n. 8
0
/*************************************(*TcpClient::PerTransFun)*********************************************/
void *TcpClient::PerTransFun(void *object) {

	TcpClient *pt = (TcpClient *) object;
	pt->setstatus(true);
	time_t startTime = time(NULL);
	time_t endTime = time(NULL);

	//创建需要发送的消息sendMsg

	cout << "Client(" << getpid() << "):Packet send begin at "
			<< asctime(localtime(&endTime));

	while ((time(NULL) - startTime) <= TESTDURATION) {
		pt->period.tv_sec = PERIODSENDMSGSEC;
		pt->period.tv_usec = PERIODSENDMSGUSEC;
		int status = select(0, NULL, NULL, NULL, &(pt->period));
		if (0 == status) {
			pt->senddata(pt->clientMsg());

		}
	}

	//cout << "Client(" << getpid() << "):go into sleep! "<<endl;
	//sleep(KEEPALIVEDURATION);

	pt->setstatus(false);
	endTime = time(NULL);
	cout << "Client(" << getpid() << "):Packet send end in "
			<< asctime(localtime(&endTime));
	pthread_exit(0);
}
Esempio n. 9
0
TcpServer::~TcpServer() {
    DEBUG;

    while (!clientConnections.isEmpty()) {
        TcpClient *client = clientConnections.takeLast();
        client->disconnect(this);
        delete client;
    }
}
Esempio n. 10
0
TcpServer::~TcpServer() {
    qDebug() << Q_FUNC_INFO;

    while (!clientConnections.isEmpty()) {
        TcpClient *client = clientConnections.takeLast();
        client->disconnect(this);
        delete client;
    }
}
Esempio n. 11
0
//===直接导出到lua里的方法===
void Net::initialize(std::string server_ip, int server_port)
{
	initialize_profile();

	tcp_client.init(server_ip, server_port);
	tcp_client.connect();

	cocos2d::Director::getInstance()->set_battle_irrelevant_update(battle_irrelevant_update);
}
int main (int argc, char** argv)
{
    QCoreApplication app(argc, argv);

    TcpClient t;
    t.connect("127.0.0.1", 4000);

    return app.exec();
}
Esempio n. 13
0
int WiFiCmdRobot::ReplyKO ()
{
     tcpClient.println("HTTP/1.1 500 Internal Server Error");
     tcpClient.println("Content-Type: text/html");
     tcpClient.println("Server: ChipkitEDH/0.1");                                   
     tcpClient.println();
     
     return SUCCESS;
                                  
}
Esempio n. 14
0
void TcpServer::incomingConnection(int handle)
{
    TcpClient *pClient = new TcpClient(this, handle);
    pClient->setSocketDescriptor(handle);
    connect(pClient, SIGNAL(clientReadData(int, QString, int, QByteArray)), \
            this, SIGNAL(clientReadData(int, QString, int, QByteArray)));
    connect(pClient, SIGNAL(clientDisConnect(int, QString, int)), \
            this, SLOT(disconnect(int, QString, int)));
    emit clientConnect(handle, pClient->peerAddress().toString(), pClient->peerPort());
    m_clientList.append(pClient);
    m_clientNum++;
}
Esempio n. 15
0
bool tcpServerClientReceive (TcpClient& client, char *data, int size)
{
	debugf("Application DataCallback : %s, %d bytes \r\n",client.getRemoteIp().toString().c_str(),size );
	debugf("Data : %s", data);
	client.sendString("sendString data\r\n", false);
	client.writeString("writeString data\r\n",0 );
	if (strcmp(data,"close") == 0)
	{
		debugf("Closing client");
		client.close();
	};
	return true;
}
Esempio n. 16
0
int main(int argc, char *argv[])
{
    TcpClient tcpClient;
    string    ip;
    int       port = 9966;
    
    if(argc >= 3) {
        for(auto i = 1; i < argc; ++i) {
            if(!string(argv[i]).compare("--help")) {
                print_usage();
            } else if(!string(argv[i]).compare("-ip")) {
                ++i;
                if(i < argc) 
                    ip = argv[i];
            } else if(!string(argv[i]).compare("-port")) {
                ++i;
                if(i < argc) 
                    port = atoi(argv[i]);
            }
        }
    }

    if(ip.empty() ) 
        print_usage();

    if(tcpClient.clientInit(ip, port, AF_INET) < 0) {
        cout << "can not connect to " << ip << ":" << port << endl;
        exit(0);
    }
    cout << "connect to " << ip << ":" << port << endl;

    Socket *cli = tcpClient.getConnection();
    if(!cli) {
        printf("getConnection() fail\n");
    }
    for(int i = 0; i < 1000; ++i) {
        char buf[1024] = {0};

        sprintf(buf, "cnt %d\n", i);
        printf("%s", buf);
        cli->write(buf, strlen(buf));
        memset(buf, 0, sizeof(buf));
        cli->read(buf, sizeof(buf));
        printf("%s", buf);
        sleep(1);
    }

    tcpClient.releaseConnection(cli);

    return 0;
}
Esempio n. 17
0
int TcpServer::processReceive(int socket)
{
    auto it = clientList.find(socket);
    if (it == clientList.end()) return 0;
    
    TcpClient* client = it->second;

    char tmpBuffer[1024];  //TODO: should get a buffer from a buffer pool
    size_t n = 1;
    while (n > 0)
    {
        if (this->stopping)
        {
            n = 0;
            break;
        }
        n = client->getSocket()->read((char*)&tmpBuffer[0], 1024);

        if (n == 0)
        {
            client->onDisconnected();
            clientList.erase(it);
            delete client;
        }
        else if (n == -1)
        {
            n = 0;
            if (errno == ECONNRESET)
            {
                client->onDisconnected();
                clientList.erase(it);
                delete client;
            }
            else 
            {
                if (errno != EAGAIN)
                {
                    LOG("Read error. Returned " << errno);
                    abort();
                }
            }
            break;
        }
        else
        {
            client->onReceive((char*)&tmpBuffer[0], n);            
        }
    }
    
    return n;
}
Esempio n. 18
0
void tcpUpdate(float dt)
{
	accumulated_time += dt;
	if (accumulated_time >= time_to_send_heart_beat)
	{
		//发送心跳包
		uint32_t empty = 4;
		tcp_client.send((unsigned char*)&empty, 4);

		accumulated_time -= time_to_send_heart_beat;
	}

	if (stage == to_receive_size)
	{
		if (tcp_client.receive((unsigned char*)&data_size, 4) == 0)
		{
			return;
		}
		data_size -= 4; //后面数据的具体长度是要减去头的4的
		receive_data = new unsigned char[data_size];
		stage = to_receive_data;
	}

	if (stage == to_receive_data)
	{
		if (tcp_client.receive(receive_data, data_size) == 0)
		{
			return;
		}

		boids::BoidsMessageHeader __msg;
		if (__msg.ParseFromArray(receive_data, data_size))
		{
			switch (__msg.type())
			{
				HANDLE_MSG(boids::AUTO_MATCH_RESPONSE, boids::MatchResponse, autoMatchResponse);
			default:
				cocos2d::log("[ERROR] unrecognized msg type: %d", __msg.type());
				break;
			}
		}
		else
		{
			cocos2d::log("[ERROR] receive a packet but not a BoidsMessageHeader. data_len: %d", data_size);
		}

		delete receive_data;
		stage = to_receive_size;
	}
}
Esempio n. 19
0
void* TcpClient::handleFunc(TcpClient* arg)
{
	TcpClient* pClient = (TcpClient*)arg;

	bool bCon(false);
	for (int i = 0; i < CONN_TIMES; i++)
	{
		bCon = pClient->getSocket()->connectToTcp("192.168.208.128", 9999);
		if (bCon)
			break;

		pClient->getSocket()->close();
		//pClient->getSocket()
	}
   
	if (bCon)
	{  
		G.m_nStatus = STATUS_CONNECTED;
		
		thread t(responseFunc, pClient);
		t.detach();		
		while (!pClient->m_bStop)
		{
			unique_lock<mutex> lock(pClient->m_writeMutex);
			if (pClient->m_writeData.getPos() == 0)
				pClient->m_writeCv.wait(lock);

			int nRet = pClient->m_socket.send(pClient->m_writeData.getBuf(), pClient->m_writeData.getPos());
			
			if (nRet < 0)
			{
				pClient->closeAndReConn();
				break;
			}
			else
			{
				pClient->m_writeData.pop(nRet);
			}
		}
		//pClient->requestLogin(G.getSeq());
	}
	else
	{  
        G.m_nStatus = STATUS_DISCONNECT;
    }     
     
    return NULL;      
}
Esempio n. 20
0
int WiFiCmdRobot::WiFiSendPicture (int16_t n)
{
  int ret=SUCCESS;
  int16_t nbytes; 
  uint8_t buf[PAYLOAD_SIZE];
  char filename[12+1];
 
  Serial.print("n: ");
  Serial.println(n);
  
  // Open the file
  sprintf(filename, "PICT%02d.jpg", n);
  if (!FilePicture.open(&root, filename, O_READ)) return FILE_OPEN_ERROR;  

  Serial.print("Open file: ");
  Serial.println(filename);

  // read from the file until there's nothing else in it:
  while ((nbytes = FilePicture.read(buf, sizeof(buf))) > 0 && ret == SUCCESS) {
       for (unsigned int idx = 0; idx<nbytes;idx++)
       {
           tcpClient.print(buf[idx]);
       }
 
  }// while
  
  //Close file
  if (!FilePicture.close()) return FILE_CLOSE_ERROR;  
  
  return SUCCESS;
}
Esempio n. 21
0
//从socket读
void TcpClient::read_cb(struct bufferevent *bev, void *arg)
{
    TcpClient *pClient = (TcpClient *)arg;
    const int MAX_LENGHT = 1024;
    char cbData[MAX_LENGHT];
    int n;
    //读数据:bufferevent_read
    //写数据:bufferevent_write
    while (n = bufferevent_read(bev, cbData, MAX_LENGHT))
    {
        if (n <= 0)
            break;
        //处理接收到的数据
        pClient->DealWithData(bev,cbData, n);
    }
}
Esempio n. 22
0
void TelnetServer::onClientComplete(TcpClient& client, bool succesfull)
{
    if ( &client == curClient)
    {
        delete commandExecutor;
        commandExecutor = nullptr;
        curClient = nullptr;
        debugf("TelnetServer onClientComplete %s", client.getRemoteIp().toString().c_str() );
    }
    else
    {
        debugf("Telnet server unconnected client close");
    }

    debugf("TelnetServer onClientComplete %s", client.getRemoteIp().toString().c_str() );
    TcpServer::onClientComplete(client, succesfull);
}
Esempio n. 23
0
void TcpServer::onClientComplete(TcpClient& client, bool succesfull)
{
	activeClients--;
	debugf("TcpSever onComplete : %s activeClients = %d\r\n",client.getRemoteIp().toString().c_str(),activeClients );
	if (clientCompleteDelegate)
	{
		clientCompleteDelegate(client,succesfull);
	}
}
Esempio n. 24
0
void * TcpClient::handleRecvMsg(void *arg)
{
	pthread_detach(pthread_self());
	TcpClient *ptc = (TcpClient*)arg;
	RecvStream recvstream,rs;
	int i,r = 0;

	while(1)
	{
		pthread_mutex_lock(&mutexRecvStream);
		if(recvbuf.size <=0)
		{
			pthread_cond_wait(&condRecv,&mutexRecvStream);
		}
		r = recvbuf.getDataFromBuf(recvstream.stream, &(recvstream.size));
		pthread_mutex_unlock(&mutexRecvStream);
		 if(r)
		 {
			 for(int t=0; t<recvstream.size;t++)
			                 printf("%02x ", recvstream.stream[t]);
			             printf("\n");
			 ptc->toOriginalMsg(recvstream.stream, recvstream.size, rs.stream, &rs.size);
			i = ptc->checkCode(rs.stream, rs.size);
			if(i<0)
			{
				continue;
			}
			if(i==1)
			{
			//parse msg
				MsgHeader header;
				header.fromStream(rs.stream);
				switch(header.msgId)
				{
					case 0x8100: handleRegisterAck(&rs);break;
					case 0x8001: handlePlatformAck(&rs);break;
					default:break;
				}
			}
			r=0;
		 }
	}
	return NULL;
}
Esempio n. 25
0
int main(int argc, char** argv){
  if (argc < 2) {
    printf ("ERROR: Chamada incorreta.\nEscreva '<nome do programa> <endereço IP> <porta>'.\n");
    return 0;
  }

  receivingBuffer = sendingBuffer = new char[512];
  matrix clientMatrix;

  TcpClient client;
  client.connect (argv[1], atoi(argv[2]));

  while (client.receive (receivingBuffer, textLength)) {
    cout << receivingBuffer;
    if (receivingBuffer[textLength-1]  == ':'){
      cin >> sendingBuffer;
      client.send (sendingBuffer);
    }
  }
Esempio n. 26
0
bool TcpServer::onClientReceive (TcpClient& client, char *data, int size)
{
	debugf("TcpSever onReceive : %s, %d bytes \r\n",client.getRemoteIp().toString().c_str(),size );
	debugf("Data : %s", data);
	if (clientReceiveDelegate)
	{
		return clientReceiveDelegate(client, data, size);
	}
	return true;
}
Esempio n. 27
0
bool TelnetServer::onClientReceive (TcpClient& client, char *data, int size)
{
    debugf("TelnetServer onClientReceive : %s, %d bytes \r\n",client.getRemoteIp().toString().c_str(),size );
    debugf("Data : %s", data);
    if (commandExecutor)
    {
        commandExecutor->executorReceive(data,size);
    }

    return true;
}
int main(int argc, char** argv)
{
    char ip[1024] = "192.168.0.50"; // Robot IP address
    TcpClient connection;
    MessageManager manager;

    ros::init(argc, argv, "state_interface");
    ros::NodeHandle n;

    JointRelayHandler jr_handler(n);

    ROS_INFO("Setting up client");
    connection.init(ip, StandardSocketPorts::STATE);
    connection.makeConnect();

    jr_handler.init(&connection);

    manager.init(&connection);
    manager.add(&jr_handler);

    manager.spin();
}
Esempio n. 29
0
void Clients::on_notify()
{
	uv_stream_t* stream;
	while (this->receive_queue.try_pop(stream))
	{
		TcpClient *available = nullptr;
		if (this->available_clients.try_pop(available))
			stream->data = available;

		if (available == nullptr)
			available = new Client();

		available->socket = reinterpret_cast<uv_tcp_t*>(stream);
		stream->data = available;

		stream->loop = &this->get_loop();
		uv_read_start(stream, &alloc_buffer, &TcpClient::on_segment);

		available->handle_connection();

		LOG(INFO) << "Client " << static_cast<void*>(stream->data) << " connected";
	}
}
Esempio n. 30
0
  void execute(){

    vector<uchar> buff;
    vector<int> param;
    param.push_back(CV_IMWRITE_JPEG_QUALITY);
    param.push_back(95);

    string LOCALHOST="127.0.0.1";//ローカルホストのIPアドレス
    int PORT=12345;//ポート番号

    while(1){
      pthread_testcancel();                 // キャンセル要求が来ていたらここで終了
      TcpClient client;
      if(!client.Init(LOCALHOST,PORT)){
	perror("connect server is failed.\n");
	return;
      }

      pthread_mutex_lock(&(this->mutex));   // 優先権を保持するまで待機
      cv::imencode(".jpg",frame,buff,param);
      pthread_mutex_unlock(&(this->mutex)); // 優先権を破棄
      
      vector<char> data;

      vector<uchar>::iterator iterator = buff.begin(); 
      while(iterator != buff.end()){
	data.push_back(static_cast<char>(*iterator));
	iterator++;
      }
      
      printf("data size is %lu\n",data.size());
      int nSend=client.Write(data);//データ受信
      
      printf("send size : %d\n",nSend);
      
    }
  }