void *connHandler(void *sock) { char buf[100], curr_char; int i; pthread_detach(pthread_self()); TCPSocket *socket = (TCPSocket *) sock; socket.recv(buf, CMD_SIZE); // If it is a FEED command if(buf.compare(FE_CMD)){ // Reset buf buf[0] = '\0'; i = 0; do{ socket.recv(&curr_char, 1); buf[i] = curr_char; i++; } while(curr_char != '\n'); // replace \n for \0 to end string buf[i] = '\0'; get_img_from_url(buf); } // If it is an ASK command else if(buf.compare(AS_CMD)){ buf[0] = '\0'; } // Echo message back to client strcpy(buf, ACK); sock->send(buf, 3); delete (TCPSocket *) sock; return NULL; }
bool GetMessage(string& msg) { static char buffer[16 * 1024]; unsigned int bytesRead = 0; while(bytesRead < sizeof(unsigned int)) { SelectInput(); int readResult = gSocket.recv(buffer + bytesRead, sizeof(unsigned int) - bytesRead); if(readResult < 0) continue; bytesRead += readResult; } // msg is prefixed with it's total length int msgLen = ntohl(*(unsigned int*)buffer); if(sizeof(unsigned int) + msgLen > sizeof(buffer)) { cerr << "message too long; aborting" << endl; abort(); } // read remaining message segments int msgRead = bytesRead - sizeof(unsigned int); char *offset = buffer + bytesRead; while (msgRead < msgLen) { if (! SelectInput()) { return false; } int readLen = sizeof(buffer) - msgRead; if(readLen > msgLen - msgRead) readLen = msgLen - msgRead; int readResult = gSocket.recv(offset, readLen); if(readResult < 0) continue; msgRead += readResult; offset += readResult; } (*offset) = 0; msg = string(buffer+sizeof(unsigned int)); return true; }
void rcv_n_chk_against_rfc864_pattern_nonblock(TCPSocket &sock) { static const size_t total_size = 1024 * 100; static const size_t buff_size = 1220; uint8_t buff[buff_size]; size_t recvd_size = 0; int time_allotted = split2half_rmng_tcp_test_time(); // [s] Timer timer; timer.start(); // Verify received data while (recvd_size < total_size) { int rd = sock.recv(buff, buff_size); TEST_ASSERT(rd > 0 || rd == NSAPI_ERROR_WOULD_BLOCK); if (rd > 0) { check_RFC_864_pattern(buff, rd, recvd_size); recvd_size += rd; } else if (rd == NSAPI_ERROR_WOULD_BLOCK) { if (timer.read() >= time_allotted) { TEST_FAIL(); break; } TEST_ASSERT_NOT_EQUAL(osEventTimeout, osSignalWait(SIGNAL_SIGIO, SIGIO_TIMEOUT).status); } else { TEST_FAIL(); break; } } timer.stop(); printf("MBED: Time taken: %fs\n", timer.read()); }
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"); }
void Dispatcher::run() { while(1) { TCPSocket* speaker = multiListener->listenToSocket(10); if(speaker!=NULL) { int cmd; speaker->recv((char*)&cmd,4); cmd = ntohl(cmd); switch(cmd) { case SESSION_ESTABLISHED: cout<<"connected"; break; case OPEN_SESSION_WITH_PEER: {string dest = ReceiveMsg(speaker); ConnectRequest(speaker->destIpAndPort(),dest);} break; case USER_LIST: sendUserList(speaker); break; case ROOM_LIST: sendRoomList(speaker); break; case MEMBERS_LIST: {string room = ReceiveMsg(speaker); sendMembersList(speaker,room);} break; case CREATE_CHAT: SetActiveChat(speaker->destIpAndPort()); break; case CLOSE_CHAT: CloseUserChat(speaker->destIpAndPort()); break; case CLOSE_SESSION_WITH_PEER: closePeer(speaker->destIpAndPort()); break; default: break; } } } }
void rcv_n_chk_against_rfc864_pattern(TCPSocket& sock) { static const size_t total_size = 1024 * 100; static const size_t buff_size = 1220; uint8_t buff[buff_size]; size_t recvd_size = 0; // Verify received data while (recvd_size < total_size) { int rd = sock.recv(buff, buff_size); TEST_ASSERT(rd > 0); check_RFC_864_pattern(buff, rd, recvd_size); recvd_size += rd; } }
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 rcv_n_chk_against_rfc864_pattern_nonblock(TCPSocket& sock) { static const size_t total_size = 1024 * 100; static const size_t buff_size = 1220; uint8_t buff[buff_size]; size_t recvd_size = 0; // Verify received data while (recvd_size < total_size) { int rd = sock.recv(buff, buff_size); TEST_ASSERT(rd > 0 || rd == NSAPI_ERROR_WOULD_BLOCK); if (rd > 0) { check_RFC_864_pattern(buff, rd, recvd_size); recvd_size += rd; } else if (rd == NSAPI_ERROR_WOULD_BLOCK) { TEST_ASSERT_NOT_EQUAL(osEventTimeout, osSignalWait(SIGNAL_SIGIO, SIGIO_TIMEOUT).status); } } }
void rcv_n_chk_against_rfc864_pattern(TCPSocket &sock) { static const size_t total_size = 1024 * 100; static const size_t buff_size = 1220; uint8_t buff[buff_size]; size_t recvd_size = 0; Timer timer; timer.start(); // Verify received data while (recvd_size < total_size) { int rd = sock.recv(buff, buff_size); TEST_ASSERT(rd > 0); if (rd < 0) { break; } check_RFC_864_pattern(buff, rd, recvd_size); recvd_size += rd; } timer.stop(); printf("MBED: Time taken: %fs\n", timer.read()); }
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; }
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++; } }
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++; } }
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);} } }
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
void ConnectionManagerIn::execute(void * arg) { ConnectionManagerIn * pthis = (ConnectionManagerIn *)arg; flog<<"Connection manager In Init...\n"; TCPSocket * socket; event_data_t event_data; try { socket = pthis->cli->getClient()->getSocket(); } catch (vortex::Exception * e) { printf("%s\n",e->what()); flog <<"Cli init:"<<e->what()<<endl; delete e; } char * buffer = (char *)malloc(5); try { if (socket->pollRead()) socket->recv(buffer,5,0); LoginResponsePacket lrp(buffer,(size_t)5); if (lrp.getHeader().length()>0) flog << "Yay got a positive response!\n"; else flog << "login failed!\n"; } catch (vortex::Exception * e) { flog << "what 1"<<e->what()<<endl; //Soit Mauvais paquet //Soit timeout du socket } free(buffer); //LOGIN OK! //On peux rentrer dans la boucle principale de protocole while (1) { flog << "Main LOOP!\n"; try { //D'abord on checks si il y a des donnees a lire avec select flog << "POLL successful!\n"; char * buffer = (char *)malloc(5); socket->recv(buffer,5,0); bitBuffer header(buffer,5); flog << "Type:" <<(int)header.readChar(false)<<endl; switch (header.readChar(false)) { case event_connect_login: flog << "login" << endl; break; case event_connect_logout: flog << "logout" << endl; break; case event_world_add: flog << "add" << endl; break; case event_world_update: flog << "update" << endl; break; case event_world_del: flog << "del" << endl; break; case event_chat_incoming: flog << "chat" << endl; break; } free(buffer); } catch (vortex::Exception * e) { flog << "what2"<<e->what()<<endl; delete e; } //Apres on check les events: } flog << "main loop end\n"; }