コード例 #1
0
ファイル: main.cpp プロジェクト: NXPmicro/mbed
void wifi_http()
{
    TCPSocket socket;
    int ret;

    ret = get_wifi()->connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2);
    TEST_ASSERT_MESSAGE(ret == 0, "Connect failed");

    // Open a socket on the network interface, and create a TCP connection to www.arm.com
    ret = socket.open(get_wifi());
    TEST_ASSERT_MESSAGE(ret == 0, "Socket open failed");
    ret = socket.connect("www.arm.com", 80);
    TEST_ASSERT_MESSAGE(ret == 0, "Socket connect failed");

    // Send a simple http request
    char sbuffer[] = "GET / HTTP/1.1\r\nHost: www.arm.com\r\n\r\n";
    int scount = socket.send(sbuffer, sizeof sbuffer);
    TEST_ASSERT_MESSAGE(scount >= 0, "Socket send failed");

    // Recieve a simple http response and check if it's not empty
    char rbuffer[64];
    int rcount = socket.recv(rbuffer, sizeof rbuffer);
    TEST_ASSERT_MESSAGE(rcount >= 0, "Socket recv error");
    TEST_ASSERT_MESSAGE(rcount > 0, "No data received");

    ret = socket.close();
    TEST_ASSERT_MESSAGE(ret == 0, "Socket close failed");

    ret = get_wifi()->disconnect();
    TEST_ASSERT_MESSAGE(ret == 0, "Disconnect failed");
}
コード例 #2
0
bool TCPConnection::sendMessageFirstSizeInInt(string ip, string text,
		int port) {
	try {
		TCPSocket *sock = new TCPSocket(ip, port);
		uint32_t size = htonl(strlen(text.c_str()));
		//sent packet size
		sock->send(&size, sizeof(size));
		//sent packet itself
		sock->send(text.c_str(), size);
		delete sock;
		return true;
	} catch (SocketException &e) {
		cerr << e.what() << endl;
		return false;
	}
	return false;
}
コード例 #3
0
bool TCPConnection::sendMessageLocal(string text,int port) {
	try {

		TCPSocket *sock = new TCPSocket("127.0.0.1", port);
		const char *echoString =text.c_str();
		int val[1];
		val[0]=strlen(echoString);
		sock->send(val, sizeof(val));
		sock->send(echoString,val[0]);
		delete sock;
		Utilities::errorCatcher("sendMessageLocal",1);

		return true;
	} catch (SocketException &e) {
		cerr << e.what() << endl;
		return false;
	}
	return false;
}
コード例 #4
0
ファイル: main.cpp プロジェクト: unfabio/furosimspark
void PutMessage(const string& msg)
{
    if (msg.empty())
        {
            return;
        }

    // prefix the message with it's payload length
    unsigned int len = htonl(msg.size());
    string prefix((const char*)&len,sizeof(unsigned int));
    string str = prefix + msg;
    gSocket.send(str.data(),str.size());
}
コード例 #5
0
ファイル: ebusd_send.cpp プロジェクト: BeeRed/ebusd
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;

}
コード例 #6
0
bool sendEMailCommand (TCPSocket &sock, const std::string &command, u32 code = 250)
{
    std::string buffer = command + "\r\n";
    u32 size = (u32)buffer.size();
    if(!command.empty())
    {
        if (sock.send ((u8 *)buffer.c_str(), size) != Sock::eSockResult_Ok)
        {
            Warning("EMAIL: Can't send data to the server");
            return false;
        }
    }

    std::string res;
    char c;
    for(;;)
    {
        size = 1;
        if (sock.receive((u8*)&c, size, false) == Sock::eSockResult_Ok)
        {
            res += c;
            if (c == '\n')
            {
                u32 c;
                Email::fromString(res, c);
                if (c != code)
                {
                    Warning ("EMAIL: EMail command '%s' returned '%s' instead of code %d on sock %s", command.substr(0, 20).c_str(), res.substr(0, res.size()-2).c_str(), code, sock.remoteAddr().asString().c_str());
                    return false;
                }
                return true;
            }
        }
        else
        {
            Warning ("EMAIL: EMail connection closed before end of line, command '%s' returned '%s' on sock %s (code %d)", command.substr(0, 20).c_str(), res.c_str(), sock.remoteAddr().asString().c_str(), code);
            return false;
        }
    }

    return true;
}
コード例 #7
0
ファイル: csocket.cpp プロジェクト: amardomingo/lsin-bot
static void* HandleTCPClient(void *sock1)  // individual client, data on STACK... might overflow...
{
	clock_t starttime = ElapsedMilliseconds(); 
	char* memory = (char*) malloc(2*SERVERTRANSERSIZE+2); // our data in 1st chunk, his reply info in 2nd
	if (!memory) return NULL; // ignore him if we run out of memory
	char* output = memory+SERVERTRANSERSIZE;
	*output = 0;
	char* buffer;
	TCPSocket *sock = (TCPSocket*) sock1;
	char IP[20];
    try {
        strcpy(memory,sock->getForeignAddress().c_str());	// get IP address
		strcpy(IP,memory);
		buffer = memory + strlen(memory) + 1;				// use this space after IP for messaging
    } catch (SocketException e)
	{ 
		ReportBug("Socket errx"); cerr << "Unable to get port" << endl;
		return Done(sock,memory);
	}
	char timeout = ' ';

	char userName[500];
	*userName = 0;
	char* user;
	char* bot;
	char* msg;
	char* prior = "";
	// A user name with a . in front of it means tie it with IP address so it remains unique 
	try{
		unsigned int len = sock->recv(buffer, SERVERTRANSERSIZE-50); // leave ip address in front alone
		memset(buffer+len,0,3); 
	
		user = buffer;
		bot = user + strlen(user) + 1;
		msg = bot + strlen(bot) + 1;

		if (!*user)
		{
			if (*bot == '1' && bot[1] == 0) // echo test to prove server running (generates no log traces)
			{
				strcpy(output,"1");
				return Done(sock,memory);
			}

			ReportBug("%s %s bot: %s msg: %s  NO USER ID \r\n",IP,GetTimeInfo()+SKIPWEEKDAY,bot,msg);
			strcpy(output,"[you have no user id]\r\n"); 
			return Done(sock,memory);
		}

		if (Blacklisted(memory,user)) // if he is blacklisted, we ignore him
		{
			PartialLogin(user,memory); // sets LOG file so we record his messages
			Log(SERVERLOG,"%s %s/%s %s msg: %s  BLOCKED \r\n",IP,user,bot,GetTimeInfo()+SKIPWEEKDAY,msg);
			strcpy(output,"[ignoring you.]\r\n"); //   response is JUST this
 			Log(STDUSERLOG,"blocked %s  =>  %s\r\n",msg,output);
			return Done(sock,memory);
		}
		strcpy(userName,user);

		// wait to get attention of chatbot server, timeout if doesnt come soon enough

		bool ready = ClientGetChatLock( ANSWERTIMELIMIT - (ElapsedMilliseconds() - starttime) ); // chatlock  ...
		if (!ready)  // if it takes to long waiting to get server attn, give up
		{
 			PartialLogin(userName,memory); // sets LOG file so we record his messages
			switch(random(4))
			{
				case 0: strcpy(output,"Hey, sorry. Had to answer the phone. What was I saying?"); break;
				case 1: strcpy(output,"Hey, sorry. There was a salesman at the door. Where were we?"); break;
				case 2: strcpy(output,"Hey, sorry. Got distracted. What did you say?"); break;
				case 3: strcpy(output,"Hey, sorry. What did you say?"); break;
			}
			Log(STDUSERLOG,"Timeout waiting for service: %s  =>  %s\r\n",msg,output);
			return Done(sock,memory);
		}

	  } catch (...)  
	  {
			ReportBug("***%s client presocket failed %s\r\n",IP,GetTimeInfo()+SKIPWEEKDAY);
 			return Done(sock,memory);
	  }
	 clock_t serverstarttime = ElapsedMilliseconds(); 
	 try{
 		chatWanted = true;	// indicate we want the chatbot server - no other client can get chatLock while this is true
		clientBuffer = memory; 
		int remain = ANSWERTIMELIMIT - (ElapsedMilliseconds() - starttime);

		if (!ClientWaitForServer(memory,msg,remain)) // release lock, loop wait for data,  and maybe we give up waiting for him
		{
			timeout = '*';
			switch(random(4))
			{
				case 0: strcpy(output,"Hey, sorry. Had to answer the phone. What was I saying?"); break;
				case 1: strcpy(output,"Hey, sorry. There was a salesman at the door. Where were we?"); break;
				case 2: strcpy(output,"Hey, sorry. Got distracted. What did you say?"); break;
				case 3: strcpy(output,"Hey, sorry. What did you say?"); break;
			}
		}
		unsigned int len = strlen(output);
		if (len) sock->send(output, len);
		prior = output + len + 1;			// bot prior message to us
} catch (...)  {
		printf("client socket fail\r\n");
		ReportBug("***%s client socket failed %s \r\n",IP,GetTimeInfo()+SKIPWEEKDAY);}
	delete sock;
	char* date = GetTimeInfo()+SKIPWEEKDAY;
	date[15] = 0;	// suppress year
	clock_t endtime = ElapsedMilliseconds(); 

	char* prior1 = prior + strlen(prior) + 1;
	int volleys = atoi(prior1);
	if (*msg) Log(SERVERLOG,"%c %s %s/%s %s time:%d/%d v:%d   msg: %s  =>  %s   <= %s\n",timeout,IP,user,bot,date, (int)(endtime - starttime),(int)(endtime - serverstarttime),volleys,msg,output,prior);
	else Log(SERVERLOG,"%c %s %s/%s %s start  =>  %s   <= %s\n",timeout,IP,user,bot,date,output,prior);
	free(memory);
#ifndef WIN32
	pthread_exit(0);
#endif
	return NULL;
}
コード例 #8
0
ファイル: csocket.cpp プロジェクト: amardomingo/lsin-bot
void RegressLoad()// test load for a server
{
	
	FILE* in = fopen("REGRESS/bigregress.txt","rb");
	if (!in) return;
	
	// treat each invocation as a new judge
	FILE* in1 = fopen("load.txt","rb");
	int id = 0;
	char buffer[8000];
	if (in1)
	{
		fread(buffer,1,100,in1);
		fclose(in1);
		id = atoi(buffer);
	}
	++id;
	FILE* out = fopen("load.txt","wb");
	fprintf(out,"%d\r\n",id);
	fclose(out);

	printf("\r\n\r\n** Load %d launched\r\n",id);
	char data[MAX_WORD_SIZE];
	char from[100];
	sprintf(from,"%d",id);
	char* bot = "";
	sprintf(logbuffer,"log-%s.txt",from);
	unsigned int msg = 0;
	unsigned int volleys = 0;
	unsigned int longVolleys = 0;
	unsigned int xlongVolleys = 0;

	int maxTime = 0;
	int cycleTime = 0;
	int currentCycleTime = 0;
	int avgTime = 0;

	// message to server is 3 strings-   username, botname, null (start conversation) or message
	echo = 1;
	char* ptr = data;
	strcpy(ptr,from);
	ptr += strlen(ptr) + 1;
	strcpy(ptr,bot);
	ptr += strlen(ptr) + 1;
	*buffer = 0;
	int counter = 0;
	while (1)
	{

		if (!ReadALine(revertBuffer+1,in)) break; // end of input
		// when reading from file, see if line is empty or comment
		char word[MAX_WORD_SIZE];
		char* at = SkipWhitespace(revertBuffer+1); 
		ReadCompiledWord(at,word);
		if (!*word || *word == '#' || *word == ':') continue;

		strcpy(ptr,revertBuffer+1);
		try 
		{
			unsigned int len = (ptr-data) + 1 + strlen(ptr);
			++volleys;
			clock_t start_time = ElapsedMilliseconds();

			TCPSocket *sock = new TCPSocket(serverIP, port);
			sock->send(data, len );
	
			int bytesReceived = 1;              // Bytes read on each recv()
			int totalBytesReceived = 0;         // Total bytes read
			char* base = ptr;
			while (bytesReceived > 0) 
			{
				// Receive up to the buffer size bytes from the sender
				bytesReceived = sock->recv(base, MAX_WORD_SIZE);
				totalBytesReceived += bytesReceived;
				base += bytesReceived;
			}
			clock_t end_time = ElapsedMilliseconds();
	
			delete(sock);
			*base = 0;
			int diff = end_time - start_time;
			if (diff > maxTime) maxTime = diff;
			if ( diff > 2000) ++longVolleys;
			if (diff > 5000) ++ xlongVolleys;
			currentCycleTime += diff;

			// chatbot replies this
			printf("real:%d avg:%d max:%d volley:%d 2slong:%d 5slong:%d %s => %s\r\n",diff,avgTime,maxTime,volleys,longVolleys,xlongVolleys,ptr,base);
		}
		catch(SocketException e) { printf("failed to connect to server\r\n"); exit(0);}
		if (++counter == 100) 
		{
			counter = 0;
			cycleTime = currentCycleTime;
			currentCycleTime = 0;
			avgTime = cycleTime / 100;
		}
		else msg++;
	}
}
コード例 #9
0
ファイル: csocket.cpp プロジェクト: amardomingo/lsin-bot
void Load()// test load for a server
{
	// treat each invocation as a new judge
	FILE* in = fopen("load.txt","rb");
	int id = 0;
	char buffer[1000];
	if (in)
	{
		fread(buffer,1,100,in);
		fclose(in);
		id = atoi(buffer);
	}
	++id;
	FILE* out = fopen("load.txt","wb");
	fprintf(out,"%d\r\n",id);
	fclose(out);

	printf("\r\n\r\n** Load %d launched\r\n",id);
	char data[MAX_WORD_SIZE];
	char from[100];
	sprintf(from,"%d",id);
	char* bot = "";
	sprintf(logbuffer,"log-%s.txt",from);
	unsigned int msg = 0;
	unsigned int volleys = 0;
	unsigned int longVolleys = 0;
	unsigned int xlongVolleys = 0;
	char* messages[] = {
		"What is an apple?",
		"What is a toy?",
		"What is an elephant?",
		"What is a pear?",
		"What is swimming?",
		"What is the meaning of life?",
		"What is a deal?",
		"What is an exercise?",
		"What is the point?",
		"Where is my toy?",
		"What is a bird?",
		"What is a tiger?",
		"What is a lion?",
		"What is a seahorse?",
		"What is a sawhorse?",
		"What is an egg?",
		"What is a dinosaur?",
		"What is a peach?",
		"What is a banana?",
		"What is a goose?",
		"What is a duck?",
		"What is a tomboy?",
		"What is purple?",
		0,
	};

	int maxTime = 0;
	int cycleTime = 0;
	int currentCycleTime = 0;
	int avgTime = 0;

	// message to server is 3 strings-   username, botname, null (start conversation) or message
	echo = 1;
	char* ptr = data;
	strcpy(ptr,from);
	ptr += strlen(ptr) + 1;
	strcpy(ptr,bot);
	ptr += strlen(ptr) + 1;
	while (1)
	{

		strcpy(ptr,messages[msg]);
		try 
		{
			unsigned int len = (ptr-data) + 1 + strlen(ptr);
			++volleys;
			clock_t start_time = ElapsedMilliseconds();

			TCPSocket *sock = new TCPSocket(serverIP, port);
			sock->send(data, len );
	
			int bytesReceived = 1;              // Bytes read on each recv()
			int totalBytesReceived = 0;         // Total bytes read
			char* base = ptr;
			while (bytesReceived > 0) 
			{
				// Receive up to the buffer size bytes from the sender
				bytesReceived = sock->recv(base, MAX_WORD_SIZE);
				totalBytesReceived += bytesReceived;
				base += bytesReceived;
			}
			clock_t end_time = ElapsedMilliseconds();
	
			delete(sock);
			*base = 0;
			int diff = end_time - start_time;
			if (diff > maxTime) maxTime = diff;
			if ( diff > 2000) ++longVolleys;
			if (diff > 5000) ++ xlongVolleys;
			currentCycleTime += diff;

			// chatbot replies this
			printf("real:%d avg:%d  max:%d   volleys:%d  2slong:%d 5slong:%d\r\n",diff,avgTime,maxTime,volleys,longVolleys,xlongVolleys);
		}
		catch(SocketException e) { printf("failed to connect to server\r\n"); exit(0);}
		if (messages[msg+1] == 0) 
		{
			msg = 0;
			cycleTime = currentCycleTime;
			currentCycleTime = 0;
			avgTime = cycleTime / 23;
		}
		else msg++;
	}
}
コード例 #10
0
ファイル: csocket.cpp プロジェクト: amardomingo/lsin-bot
void Dual(char* login)// test client for a server
{
	printf("\r\n\r\n** Dual launched\r\n");
	char data[MAX_WORD_SIZE];
	char data1[MAX_WORD_SIZE];
	
	char* from = login;
	char* separator = strchr(from,':'); // login is username  or  username:botname
	sprintf(logbuffer,"log-%s.txt",from);

	// message to server is 3 strings-   username, botname, null (start conversation) or message
	char* ptr = data;
	strcpy(ptr,from);
	ptr += strlen(ptr) + 1;
	strcpy(ptr,"");
	ptr += strlen(ptr) + 1;
	echo = 1;
	*ptr = 0; // null message - start conversation

	char* ptr1 = data1;
	strcpy(ptr1,from);
	strcat(ptr1,"1");	// extended id
	ptr1 += strlen(ptr1) + 1;
	strcpy(ptr1,"");
	ptr1 += strlen(ptr1) + 1;
	*ptr1 = 0; // null message - start conversation

	while (1)
	{
		try 
		{
			unsigned int len = (ptr-data) + 1 + strlen(ptr);
			TCPSocket *sock = new TCPSocket(serverIP, port);
			sock->send(data, len );

			int bytesReceived = 1;              // Bytes read on each recv()
			char* base = ptr;
			while (bytesReceived > 0) 
			{
				// Receive up to the buffer size bytes from the sender
				bytesReceived = sock->recv(base, MAX_WORD_SIZE);
				base += bytesReceived;
			}
			delete(sock);
			*base = 0;

			// now do secondary message
			strcpy(ptr1,ptr);	// put one into the other
			len = (ptr1-data1) + 1 + strlen(ptr1);
			sock = new TCPSocket(serverIP, port);
			sock->send(data1, len );

			bytesReceived = 1;              // Bytes read on each recv()
			base = ptr1;
			while (bytesReceived > 0) 
			{
				// Receive up to the buffer size bytes from the sender
				bytesReceived = sock->recv(base, MAX_WORD_SIZE);
				base += bytesReceived;
			}
			delete(sock);
			*base = 0;

			strcpy(ptr,ptr1);	// put one into the other
		}
		catch(SocketException e) { printf("failed to connect to server\r\n"); exit(0);}
	}
}
コード例 #11
0
void ThreaddedNetwork::inThreadUpdate()
{ 
  std::string currentMessage = "";
  char buffer[RCVBUFSIZE];
  int recvMsgSize;
  bool hasStart = false;
  while(true)
  {
    TCPSocket* sock = m_servSock.accept();
    std::cout <<"Got Connection\n";
    recvMsgSize = 1; // set to one just so we enter the loop
    while(recvMsgSize > 0)
    {
      // clear the input buffer
      memset(buffer, 0, RCVBUFSIZE);
      // get data from the socket
      recvMsgSize = sock->recv(buffer, RCVBUFSIZE);
      std::cout << "msg: ";
      std::cout << buffer << "\n";
      // iterate over the recieved data
      for(int i=0; i<recvMsgSize; i++)
      {
        // if we're recording a message
        if(hasStart)
        {
          // if this is the end of the message
          if(buffer[i] == ']')
          {
            // send the message to the main thread
            q_new_messages.push(currentMessage);
            // stop recording messages
            hasStart = false;
          }
          // if this is not the end of the message
          else
          {
            // add this character to the end of the current messsage
            currentMessage += buffer[i];
          }
        }
        // if we recieve a new start character
        if(buffer[i] == '[')
        {
          // start recording
          hasStart = true;
          // reset the current message
          currentMessage = "";
        } // end if
      } // end for
      //sock->send(buffer,recvMsgSize);
      std::string outgoing = "";
      for(int i=0; i<q_outgoing_messages.size(); i++)
      {
        outgoing += "[";
        outgoing += q_outgoing_messages.at(i);
        outgoing += "]";
      }
      std::cout << "outgoing:\n" << outgoing << "\n";
      sock->send("[Good]",6);
      if(outgoing.length() > 0)
      {
        sock->send(outgoing.c_str(), outgoing.length());
      }
      sock->send("\n",1);
      std::cout << "Closing connection\n";
    } // end while
    delete sock;
  } // end while
} // end inThreadUpdate
コード例 #12
0
int doClientTask (const char *pszRemoteHost, unsigned short usRemotePort, bool bUseMockets, Stats *pStats)
{
    int rc;
    static char buf [1024];
    static bool bBufInitialized;

    if (!bBufInitialized) {
        srand (1234);
		for (int i = 0; i < sizeof (buf); i++) {
            buf[i] = (char) rand();
        }
        bBufInitialized = true;
    }

    if (bUseMockets) {
        StreamMocket mocket;
        if (0 != (rc = mocket.connect (pszRemoteHost, usRemotePort))) {
            fprintf (stderr, "doClientTask: failed to connect using mockets to remote host %s on port %d; rc = %d\n",
                     pszRemoteHost, usRemotePort, rc);
            return -1;
        }
        mocket.registerPeerUnreachableWarningCallback (unreachablePeerCallback, NULL);

        int iDataSize = 1024*1024;
        int iBytesSent = 0;
        int64 i64StartTime = getTimeInMilliseconds();
        mocket.send (&iDataSize, sizeof (iDataSize));
        while (iBytesSent < iDataSize) {
            mocket.send (buf, sizeof (buf));
            iBytesSent += sizeof (buf);
        }
        char chReply = 0;
        mocket.receive (&chReply, 1);
        if (chReply != '.') {
            fprintf (stderr, "doClientTask: failed to receive . from remote host\n");
            return -2;
        }
        int64 i64EndTime = getTimeInMilliseconds();
        int iTime = (int) (getTimeInMilliseconds() - i64StartTime);

        pStats->update ((double) (i64EndTime - i64StartTime));
        // Save results to a file
        FILE *file = fopen ("stats-client-streamMockets-cpp.txt", "a");
        if (file == NULL) {
            fprintf (stderr, "failed to append to file stats-mockets-cpp.txt\n");
            return -3;
        }
        fprintf (file, "[%lu]\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", (unsigned long) (getTimeInMilliseconds()/1000), iTime, 
                 mocket.getStatistics()->getSentPacketCount(),
                 mocket.getStatistics()->getSentByteCount(),
                 mocket.getStatistics()->getReceivedPacketCount(),
                 mocket.getStatistics()->getReceivedByteCount(),
                 mocket.getStatistics()->getRetransmitCount(),
                 mocket.getStatistics()->getDuplicatedDiscardedPacketCount(),
                 mocket.getStatistics()->getNoRoomDiscardedPacketCount());
                 /*mocket.getStatistics()->getDiscardedPacketCounts()._iBelowWindow,
                 mocket.getStatistics()->getDiscardedPacketCounts()._iNoRoom,
                 mocket.getStatistics()->getDiscardedPacketCounts()._iOverlap,
                 mocket.getStatistics()->getTransmitterWaitCounts()._iPacketQueueFull,
                 mocket.getStatistics()->getTransmitterWaitCounts()._iRemoteWindowFull);*/

        fclose (file);

        mocket.close();
    }
    else {
        TCPSocket socket;
        if (0 != (rc = socket.connect (pszRemoteHost, usRemotePort))) {
            fprintf (stderr, "doClientTask: failed to connect using sockets to remote host %s on port %d; rc = %d\n",
                     pszRemoteHost, usRemotePort, rc);
            return -3;
        }

        int iDataSize = 1024*1024;
        int iBytesSent = 0;
        int64 i64StartTime = getTimeInMilliseconds();
        socket.send (&iDataSize, sizeof (iDataSize));
        while (iBytesSent < iDataSize) {
            socket.send (buf, sizeof (buf));
            iBytesSent += sizeof (buf);
        }
        char chReply = 0;
        socket.receive (&chReply, 1);
        if (chReply != '.') {
            fprintf (stderr, "doClientTask: failed to receive . from remote host\n");
            return -4;
        }
        int64 i64EndTime = getTimeInMilliseconds();
        int iTime = (int) (getTimeInMilliseconds() - i64StartTime);

        pStats->update ((double) (i64EndTime - i64StartTime));

        // Save results to a file
        FILE *socfile = fopen ("statsSM-client-sockets-cpp.txt", "a");
        if (socfile == NULL) {
            fprintf (stderr, "failed to append to file statsSM-mockets-cpp.txt\n");
            return -3;
        }
    	fprintf (socfile, "[%lu]\t%d\t\n", (unsigned long) (getTimeInMilliseconds()/1000), iTime);

        fclose (socfile);

        socket.disconnect();
    }
    return 0;
}
コード例 #13
0
int doClientTask (const char *pszRemoteHost, unsigned short usRemotePort, bool bUseMockets)
{
    int rc;
    static char buf [1024];
    static bool bBufInitialized;

    if (!bBufInitialized) {
        srand (1234);
        for (int i = 0; i < sizeof (buf); i++) {
            buf[i] = (char) rand();
        }
        bBufInitialized = true;
    }

    if (bUseMockets) {
        Mocket *pm = new Mocket();
        pm->registerPeerUnreachableWarningCallback (unreachablePeerCallback, NULL);

        puts ("doClientTask: Using Mockets:Before connect");
        if (0 != (rc = pm->connect (pszRemoteHost, usRemotePort))) {
            fprintf (stderr, "doClientTask: failed to connect using Mockets to remote host %s on port %d; rc = %d\n",
                     pszRemoteHost, usRemotePort, rc);
            puts ("doClientTask: Unable to connect");
            delete pm;
            return -11;
        }
        
        MessageSender rlsq = pm->getSender (true, true);
        MessageSender ursq = pm->getSender (false, true);

        // open stats file
        FILE *file = fopen (CLIENT_STATS_FILENAME, "a");
        if (file == NULL) {
            fprintf (stderr, "failed to append to file %s\n", CLIENT_STATS_FILENAME);
            return -12;
        }

        // mockets client code
        for (int i = 0; continue_flag; ++i) {
            // write sequence number in the first 4 bytes
            *((uint32*)buf) = EndianHelper::htonl ((uint32)i); 
            if (0 == (i % PACKET_PER_SEC)) {
                // send one reliable sequenced packet per second
                rlsq.send (buf, sizeof (buf));
            } else {
                // send an unreliable sequenced packet
                ursq.send (buf, sizeof (buf));
            }            
            sleepForMilliseconds (20);
        }

        fclose (file);
        pm->close();
        delete pm;
    } else {
        TCPSocket socket;
        puts ("doClientTask: Using Sockets:Before connect");
        if (0 != (rc = socket.connect (pszRemoteHost, usRemotePort))) {
            fprintf (stderr, "doClientTask: failed to connect using sockets to remote host %s on port %d; rc = %d\n",
                     pszRemoteHost, usRemotePort, rc);
            puts ("doClientTask: Unable to connect");
            return -11;
        }

        // open stats file
        FILE *file = fopen (CLIENT_STATS_FILENAME, "a");
        if (file == NULL) {
            fprintf (stderr, "failed to append to file %s\n", CLIENT_STATS_FILENAME);
            return -12;
        }

        // sockets client code
        for (int i = 0; continue_flag; ++i) {
            // write sequence number in the first 4 bytes
            *((uint32*)buf) = EndianHelper::htonl ((uint32)i); 
            socket.send (buf, sizeof (buf));
            sleepForMilliseconds (20);
        }

        fclose (file);
        socket.disconnect();
    }

    return 0;
}
コード例 #14
0
ファイル: ebusctl.cpp プロジェクト: Quantim/ebusd
void connect(const char* host, uint16_t port, char* const *args, int argCount)
{

	TCPClient* client = new TCPClient();
	TCPSocket* socket = client->connect(host, port);

	bool once = args != NULL && argCount > 0;
	if (socket != NULL) {
		do {
			string message;
			bool listening = false;

			if (!once) {
				cout << host << ": ";
				getline(cin, message);
			}
			else {
				for (int i = 0; i < argCount; i++) {
					if (i > 0)
						message += " ";
					bool quote = strchr(args[i], ' ') != NULL && strchr(args[i], '"') == NULL;
					if (quote)
						message += "\"";
					message += args[i];
					if (quote)
						message += "\"";
				}
			}

			message += '\n';
			socket->send(message.c_str(), message.size());

			if (strcasecmp(message.c_str(), "Q") == 0
			|| strcasecmp(message.c_str(), "QUIT") == 0
			|| strcasecmp(message.c_str(), "STOP") == 0)
				break;

			if (message.length() > 0) {
				if (strcasecmp(message.c_str(), "L") == 0
				|| strcasecmp(message.c_str(), "LISTEN") == 0) {
					listening = true;
					while (listening && !cin.eof()) {
						string result(fetchData(socket, listening));
						cout << result;
						if (strcasecmp(result.c_str(), "LISTEN STOPPED") == 0)
							break;
					}
				}
				else
					cout << fetchData(socket, listening);
			}

		} while (!once && !cin.eof());

		delete socket;

	}
	else
		cout << "error connecting to " << host << ":" << port << endl;

	delete client;
}
コード例 #15
0
	void ListenTask::run()
	{
		fd_set readers;
		// Accept connections
		while ( ! exitRequired() )
		{
			try
			{
				// Get and setup the new socket
				FD_ZERO( &readers );
				FD_SET( _ListenSock.descriptor(), &readers );
				int res = ::select( 1, &readers, NULL, NULL, NULL ); /// Wait indefinitely

				if ( res == -1)
				{
					continue;
				}
				MessageBox(NULL, "hint", "before accept", MB_OK);
				TCPSocket *newSock = _ListenSock.accept();
				MessageBox(NULL, "hint", "after accept", MB_OK);
				if (newSock)
				{
					u8 buffer[512];
					size_t len = 512;
					//newSock->receive(buffer, len);
					//MessageBox(NULL, (char*)buffer, "server rec", MB_OK);
					std::string sendMessage("hello i am the server");
					len = sendMessage.size();
					newSock->send((u8*)sendMessage.c_str(), len);
					MessageBox(NULL, "hint", "after send", MB_OK);
					sendMessage = "hello i am the server 2";
					newSock->send((u8*)sendMessage.c_str(), len);
					MessageBox(NULL, "hint", "after send 2", MB_OK);
					//newSock->close();
					//delete newSock;
				}
/*
				if (newSock != NULL)
				{
					CServerBufSock *bufsock = new CServerBufSock( newSock );
					LNETL1_DEBUG( "LNETL1: New connection : %s", bufsock->asString().c_str() );
					bufsock->setNonBlocking();
					bufsock->setMaxExpectedBlockSize( _MaxExpectedBlockSize );
					if ( _Server->noDelay() )
					{
						bufsock->Sock->setNoDelay( true );
					}

					// Notify the new connection
					bufsock->advertiseConnection( _Server );

					// Dispatch the socket into the thread pool
					_Server->dispatchNewSocket( bufsock );
				}

*/
				//NbLoop++;
			}
			catch (const ESocket &e)
			{
				// It can occur when too many sockets are open (e.g. 885 connections)
			}
		}
	}