static void fileTransfer(struct mg_connection *conn) { char action[10]; char protocol[10]; char filename[50]; mg_get_var(conn, "act", action, sizeof(action)); mg_get_var(conn, "via", protocol, sizeof(protocol)); mg_get_var(conn, "file", filename, sizeof(filename)); if (!strcmp(action, "Download")) { if (!strcmp(protocol, "udp")) { sendMsg(filename, 0); initUDPClient(filename+2, IP); } else { initCDTCP(filename); } } else { if (!strcmp(protocol, "udp")) { sendMsg(filename, 0); initUDPServer(filename+2, IP); } else { sendMsg(filename, 0); } } }
//处理网络数据 void Robot::processNetEpoll(void) { //接受Epoll返回的状态值 RobotNetEpoll::EpollDataStatus epollStatus; //左轮速度,右轮速度 int leftSpeed, rightSpeed; //nenents:当前触发的事件数,s为开始(Start)/e为结束(End)/b为基(Base) int nevents, i, s, e, b; int fd; while(true) { //阻塞接收可用事件数 nevents = netEpoll->handleEvents(); //对每一个事件进行处理 for(i = 0; i < nevents; ++i) { b = 0; //初始化缓冲区长度 bufLen = SOCKET_BUFF_SIZE; //处理事件,并将收到的数据拷贝到socketBuf中。需要关注缓冲区溢出问题 //这里的fd都为值结果参数,bufLen是以指针形式传入 //------------------ //epollStatus返回事件类型,socketBuf返回数据首地址,bufLen返回数据长度, fd返回当前事件来源描述符 //------------------ epollStatus = netEpoll->DispactchEvent(i, socketBuf, &bufLen, fd); //如果值结果参数为初始化长度,则认为数据过多,溢出处理 if(unlikely(bufLen == SOCKET_BUFF_SIZE)) continue; switch(epollStatus) { //有数据返回处理 case RobotNetEpoll::EpollSuccessWithData://{ //使用while,是为了预防一次性接受到多组数据帧 while(1) { //检索完整的数据帧 s = b; while((s < bufLen) && (socketBuf[s] != RobotPacket::Start)) {++s;} if(s >= bufLen) break; e = s + 1; while((s < bufLen) && (socketBuf[e] != RobotPacket::End)) {++e;} if(e >= bufLen) break; b = e + 1; //对帧的完整性进行初选,依据是长度 if((*(socketBuf + s + 6) + 8) != (e-s)) continue; //对于完整的帧进行封装 robotPacketExternal.finalizePacket(socketBuf + s, e - s + 1); #ifdef PACKET_HAVE_SUM_VERIFY //对帧的完整性进行校验,依据是校验码 if(!robotPacketExternal.verifyCheckSum()) continue; #endif //robotPacketExternal.printHex(); //获取帧的属性 switch(robotPacketExternal.getCommandByIndex()) { #ifdef ROBOT_SENSOR_DATA_DELAY_SEND case RobotPacketExternal::UPLINK_DATA_RETURN://0xB3 { minAck = robotPacketExternal.getIdByIndex(); PRINT("收到ACK编号为%d",minAck); } break; #endif //数据帧为带参数的控制帧 case RobotPacketExternal::DOWNLINK_CONTROL_WITHARGS_COMMAND://0x33 { //控制目标为灯 if(unlikely(RobotPacketExternal::OBJECT_LIGHT == robotPacketExternal.getByteByIndex(4)))//0x04 { //灯关 if(0x03 == robotPacketExternal.getByteByIndex(7)) { robotLightTask->setLight(0, 0x00); robotLightTask->doTask(); mediator->send(robotLightTask->getTaskBuf(), robotLightTask->getTaskBufLen()); } //灯开 else if(0x02 == robotPacketExternal.getByteByIndex(7)) { robotLightTask->setLight(0, 0x01); robotLightTask->doTask(); mediator->send(robotLightTask->getTaskBuf(), robotLightTask->getTaskBufLen()); } break; } //<模式切换> else if(unlikely(RobotPacketExternal::OBJECT_MODE == robotPacketExternal.getByteByIndex(4)))//0x03 { //modeLock.setMode(!modeLock.getMode()); // //上一个状态为手柄模式,转换为智能避障模式,否则转换为手柄模式 if(modeLock.getMode() == RobotModeLock::MODE_JOYSTICK) { mediator->serialResume(); modeLock.setMode(RobotModeLock::MODE_WANDER); } else { mediator->serialSuspend(); modeLock.setMode(RobotModeLock::MODE_JOYSTICK); } PRINT("《《《《《《《收到模式切换命令,切换为到[%s]》》》》》》\n", (modeLock.getMode() == RobotModeLock::MODE_JOYSTICK) ? "手柄模式": "智能模式"); #ifdef ROBOT_HAVE_LOG #endif //robotPoint.setPose(0,0,0); //oldRobotPoint.setPose(0, 0, 0); break; } //<电机控制> else if(likely(RobotPacketExternal::OBJECT_MOTOR == robotPacketExternal.getByteByIndex(4)))//0x01 { if(modeLock.getMode() == RobotModeLock::MODE_JOYSTICK) { leftSpeed = judgeLeftSpeed( robotPacketExternal.getByteByIndex(7), robotPacketExternal.getByteByIndex(8)); rightSpeed = judgeRightSpeed( robotPacketExternal.getByteByIndex(7), robotPacketExternal.getByteByIndex(8)); /* if(leftSpeed > 0 && rightSpeed > 0)//前进 if(disObs[3] <= 70) break; if(leftSpeed < 0 && rightSpeed < 0)//后退 if(disObs[9] <= 70) break;*/ PRINT("1发送给机器人的控制速度:左轮[%hd]-右轮[%hd]\n",leftSpeed, rightSpeed); #ifdef ROBOT_HAVE_LOG #endif robotWheelTask->setWheel(leftSpeed, rightSpeed); robotWheelTask->doTask(); mediator->send(robotWheelTask->getTaskBuf(), robotWheelTask->getTaskBufLen()); } } //<上位机设置机器人目标坐标点> else if(unlikely(RobotPacketExternal::OBJECT_COORS== robotPacketExternal.getByteByIndex(4)))//0x013 { int tx = RobotMath::charToSignedShort( robotPacketExternal.getByteByIndex(7), robotPacketExternal.getByteByIndex(8)); int ty = RobotMath::charToSignedShort( robotPacketExternal.getByteByIndex(9), robotPacketExternal.getByteByIndex(10)); PRINT("设置机器人坐标为%d,%d",tx,ty); setGoal(tx, ty, 0); } //<收到前面机器人存在信息> else if(unlikely(RobotPacketExternal::OBJECT_LINKS_FRONT== robotPacketExternal.getByteByIndex(4)))//0x0D { //robotPacketExternal.printHex(); //前面机器人编号 frontRobotNo = robotPacketExternal.getByteByIndex(5); map<int, string>::iterator iter = socketMap.find(frontRobotNo); if(iter != socketMap.end()) { setHaveFrontRobot(true); //如前边的机器人已经连接 if(!getFrontRobotIsConnected()) { setFrontRobotIp((iter->second).c_str(), strlen((iter->second).c_str())); semaphoreFlag = 1; //将信号灯挂出 semaPhore->Post(); } else { //如果新设置的前方机器人IP地为新的IP地址 if(strcmp(frontRobotIp, (iter->second).c_str()) != 0) { frontRobotSocket->close(); RELEASE_HEAP_MEMORY(frontRobotSocket); frontRobotSocket = new RobotSocket(); setFrontRobotIp((iter->second).c_str(), strlen((iter->second).c_str())); semaphoreFlag = 1; //将信号灯挂出 semaPhore->Post(); } } } } //<收到后面机器人存在信息> else if(unlikely(RobotPacketExternal::OBJECT_LINKS_BACK== robotPacketExternal.getByteByIndex(4)))//0x0E { //robotPacketExternal.printHex(); //后面机器人编号 backRobotNo = robotPacketExternal.getByteByIndex(5); map<int, string>::iterator iter = socketMap.find(backRobotNo); if(iter != socketMap.end()) { //setBackRobotIp(socketMap[backRobotNo].c_str(), sizeof(socketMap[backRobotNo].c_str())); //PRINT("%s",(iter->second).c_str()); setHaveBackRobot(true); if(!getBackRobotIsConnected()) { setBackRobotIp((iter->second).c_str(), strlen((iter->second).c_str())); semaphoreFlag = 1; semaPhore->Post(); } else { //如果新设置的后方机器人IP地位新的IP地址 if(strcmp(backRobotIp,(iter->second).c_str()) != 0) { backRobotSocket->close(); RELEASE_HEAP_MEMORY(backRobotSocket); backRobotSocket = new RobotSocket(); setBackRobotIp((iter->second).c_str(), strlen((iter->second).c_str())); semaphoreFlag = 1; //将信号灯挂出 semaPhore->Post(); }// for if }// for else }//for if(iter) } else if(unlikely(RobotPacketExternal::OBJECT_ALL_STOP== robotPacketExternal.getByteByIndex(4)))//0x0E { modeLock.setMode(RobotModeLock::MODE_JOYSTICK); } break; }//end for " case RobotPacketExternal::DOWNLINK_CONTROL_WITHARGS_COMMAND" break; //机器人之间的信息交换 case RobotPacketExternal::BETWEEN_ROBOTS_INFO_CHANGE: { if(fd == frontRobotFd) { frontRobotCtlWord = RobotMath::charToShort(robotPacketExternal.getByteByIndex(4), robotPacketExternal.getByteByIndex(5)); //收到编队前方机器人信息 frontRobotPoint.setX( RobotMath::charToSignedShort(robotPacketExternal.getByteByIndex(7), robotPacketExternal.getByteByIndex(8))); frontRobotPoint.setY( RobotMath::charToSignedShort(robotPacketExternal.getByteByIndex(9), robotPacketExternal.getByteByIndex(10))); frontRobotPoint.setTh( RobotMath::charToSignedShort(robotPacketExternal.getByteByIndex(11), robotPacketExternal.getByteByIndex(12))); //设置路径规划目标 setGoal(frontRobotPoint); } else if(fd == backRobotFd) { backRobotCtlWord = RobotMath::charToShort(robotPacketExternal.getByteByIndex(4), robotPacketExternal.getByteByIndex(5)); //收到编队后方机器人信息 backRobotPoint.setX( RobotMath::charToSignedShort(robotPacketExternal.getByteByIndex(7), robotPacketExternal.getByteByIndex(8))); backRobotPoint.setY( RobotMath::charToSignedShort(robotPacketExternal.getByteByIndex(9), robotPacketExternal.getByteByIndex(10))); backRobotPoint.setTh( RobotMath::charToSignedShort(robotPacketExternal.getByteByIndex(11), robotPacketExternal.getByteByIndex(12))); } else ::close(fd); }// end for "case RobotPacketExternal::BETWEEN_ROBOTS_INFO_CHANGE" break; case RobotPacketExternal::DOWNLINK_QUERY_COMMAND: break; case RobotPacketExternal::DOWNLINK_CONTROL_NOARGS_COMMAND:break; default:break; }//end for " switch(robotPacketExternal.getCommandByIndex())" }//end for " while(1) " break; case RobotNetEpoll::EpollAccept: { robotPacketExternal.finalizePacket(socketBuf, bufLen); char tmp[20]; sprintf(tmp,"%s", robotPacketExternal.getBuf()); PRINT("当前IP地址为[%s]的主机连接到该机器人", tmp); if(0 == memcmp(tmp, consoleIp, strlen(consoleIp))) { PRINT("该连接为控制台,已经准备完毕!"); consoleSocket->copy(fd, true); consoleSocket->setNonBlock(); //consoleSocket->setKeepAlive(); //控制台已经连接 setConsoleIsConnected(true); #ifdef ROBOT_SENSOR_DATA_DELAY_SEND minAck = maxAck = 1; ACK = 0; //控制台链接好,则可以将保存的文件发送过去 semaphoreFlag = 0; semaPhore->Post(); #endif } else if(0 == memcmp(tmp, frontRobotIp, strlen(frontRobotIp))) { //编队前方机器人连接 frontRobotFd = fd; //accept前方机器人的连接请求 setFrontRobotIsAccepted(true); } else if(0 == memcmp(tmp, backRobotIp, strlen(backRobotIp))) { //编队后方机器人连接 backRobotFd = fd; //accept后方机器人的连接请求 setBackRobotIsAccepted(true); } }//end for " case RobotNetEpoll::EpollAccept" break; case RobotNetEpoll::EpollError: { if(fd == consoleSocket->getFD()) { PRINT("-->链接到控制台网络被异常断开-\n"); setConsoleIsConnected(false); #ifdef ROBOT_SENSOR_DATA_DELAY_SEND semaphoreFlag = -1; semaPhore->Post(); #endif } } break; case RobotNetEpoll::EpollSuccessNoData:break; case RobotNetEpoll::EpollSocketClosed: { //某个套接字失效 if(frontRobotFd == fd) { //失效前方连接套接字 frontRobotFd = -1; setFrontRobotIsAccepted(false); PRINT("-->编队队伍中前方机器人已经主动断开至该机器人的连接<--\n"); } else if(backRobotFd == fd) { backRobotFd = -1; setBackRobotIsAccepted(false); PRINT("-->编队队伍中后方机器人已经主动断开至该机器人的连接<--\n"); } else if(fd == consoleSocket->getFD()) { PRINT("-->控制台已经主动断开至该机器人的连接<--\n"); setConsoleIsConnected(false); #ifdef ROBOT_SENSOR_DATA_DELAY_SEND semaphoreFlag = -1; semaPhore->Post(); #endif } else if(fd == UDPBroadcastSocket->getFD()) { //throw RobotException("UDP服务器出错"); RELEASE_HEAP_MEMORY(UDPBroadcastSocket); //重启UDP服务器 initUDPServer(); } }// end for " case RobotNetEpoll::EpollSocketClosed" // break; } //end for case }//end for " switch(epollStatus)" }//end for " for(i = 0; i < nevents; ++i)" } //end for "while(true)" }
int main(int argc, char *argv[]) { printf("====================== mSquared File Transfer Program ======================\n\n"); printf("Developed by: Mrinal Dhar 201325118 | Mounika Somisetty 201330076\n"); printf("Enter 'help' to get help about commands and other cool stuff this program can do.\n\n"); printf("============================================================================\n\n"); int serv_pid = 0; int udpServ_pid = 0; int i; char cmd[1024]; char *vals[49]; WEB_PORT = strdup("8000"); if(argc == 2) { bzero(IP,sizeof(IP)); strcpy(IP,argv[1]); } else { strcpy(IP, "127.0.0.1"); } serv_pid = fork(); if (serv_pid == 0) { listenSocket = socket(AF_INET,SOCK_STREAM,0); if(listenSocket<0) { // printf("ERROR WHILE CREATING A SOCKET\n"); } else {} // printf("[SERVER] SOCKET ESTABLISHED SUCCESSFULLY\n\n"); initServer(); close(listenSocket); } serv_pid = fork(); if (serv_pid == 0) { struct mg_server *server; // Create and configure the server server = mg_create_server(NULL, ev_handler); mg_set_option(server, "listening_port", WEB_PORT); // Serve request. // printf("Web Server Starting on port %s\n", mg_get_option(server, "listening_port")); for (;;) { mg_poll_server(server, 1000); } // Cleanup, and free server instance mg_destroy_server(&server); } periodicCheck(); char filename[50]; char chat_msg[50]; char * returncode; while (1) { printf("$> "); scanf("%[^\n]s", cmd); // printf("THIS: %s\n", cmd); getchar(); if (cmd[0]=='-') { bzero(chat_msg, 50); cpy(filename+1, cmd+1); filename[0] = 'c'; // printf("THIS=%s", filename); sendMsg(filename, 0); } else { parse(cmd, vals); if(!strcmp(vals[0], "FileDownload")) { if (!strcmp(vals[1], "TCP")) { bzero(filename, 50); cpy(filename+2, vals[2]); filename[0] = 'd'; filename[1] = 't'; if(!initCDTCP(filename)) break; } else if (!strcmp(vals[1], "UDP")) { bzero(filename, 50); cpy(filename+2, vals[2]); filename[0] = 'd'; filename[1] = 'u'; // sleep(5); if (!initUDPClient(filename+2, IP)) break; sendMsg(filename, 0); bzero(filename, 50); } } else if (!strcmp(vals[0], "FileUpload")) { if (!strcmp(vals[1], "TCP")) { // printf("DOING!!\n\n"); bzero(filename, 50); cpy(filename+2, vals[2]); filename[0] = 'u'; filename[1] = 't'; sendMsg(filename, 0); bzero(filename, 50); } else if (!strcmp(vals[1], "UDP")) { bzero(filename, 50); cpy(filename+2, vals[2]); filename[0] = 'u'; filename[1] = 'u'; returncode = sendMsg(filename, 1); // printf("GOT RCODE %s\n\n", returncode); if (returncode[0]=='y') { printf("Permission granted!\n"); sleep(2); initUDPServer(filename+2, IP); } bzero(filename, 50); } } else if(!strcmp(vals[0], "exit")) { close(listenSocket); system("killall -s 9 server"); exit(0); } else if(!strcmp(vals[0], "FileHash")) { if (!strcmp(vals[1], "--verify")) { strcpy(filename, "hv"); strcat(filename, vals[2]); sendMsg(filename, 0); } else if (!strcmp(vals[1], "--checkall")) { strcpy(filename, "hc"); sendMsg(filename, 0); } bzero(filename, 50); filename[0] = 'd'; filename[1] = 't'; strcpy(filename+2, "fileHashOutput.txt"); initCDTCP(filename); } else if(!strcmp(vals[0], "gui")) { // THE FOLLOWING CODE TRIES TO AUTOMATICALLY OPEN FIREFOX WHEN GUI IS ACTIVATED. This has some bugs. // char * ffox[1]; // ffox[0] = strdup("firefox "); // strcat(ffox[0], IP); // strcat(ffox[0], ":"); // strcat(ffox[0], WEB_PORT); // serv_pid = fork(); // if (serv_pid==0) { // if (execvp(ffox[0], ffox) < 0) { // printf("*** ERROR: exec failed\n"); // exit(1); // } // } } else if (!strcmp(vals[0], "help")) { FILE *fp = fopen("readme.txt", "rb"); while (fread(buffer, sizeof(char), 1024, fp)) { printf("%s", buffer); bzero(buffer,1024); } } else if(!strcmp(vals[0], "IndexGet")) { /* I need indexget to work on both the remote machine and the local machine and give output in four files: index-they.txt index-me.txt index-they-gui.txt index-me-gui.txt */ // handleIndex(1,0); if (!strcmp(vals[1], "--shortlist")) { strcpy(filename, "is"); sendMsg(filename, 0); handleIndex(0,0,"\0", 0, 0); } else if (!strcmp(vals[1], "--longlist")) { strcpy(filename, "il"); sendMsg(filename, 0); handleIndex(1,0,"\0", 0, 0); } else if (!strcmp(vals[1], "--regex")) { strcpy(filename, "ir"); strcat(filename, vals[2]); sendMsg(filename, 0); // handleIndex(1,1,vals[2], 0, 0); } bzero(filename, 50); filename[0] = 'd'; filename[1] = 't'; strcpy(filename+2, "index.txt"); initCDTCP(filename); } continue; } } printf("\nClosing connection2\n"); return 0; }
void initServer() { char filename[50], filesize[20]; char fbuffer[1024]; struct stat obj; // Its a general practice to make the entries 0 to clear them of malicious entry bzero((char *) &s_serv_addr,sizeof(s_serv_addr)); s_serv_addr.sin_family = AF_INET; //For a remote machine s_serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); s_serv_addr.sin_port = htons(portno); int yes=1; //char yes='1'; // use this under Solaris if (setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) { perror("setsockopt"); } if(bind(listenSocket,(struct sockaddr * )&s_serv_addr,sizeof(s_serv_addr))<0) printf("ERROR WHILE BINDING THE SOCKET\n"); else printf("[SERVER] SOCKET BINDED SUCCESSFULLY\n"); // Listening to connections if(listen(listenSocket,10) == -1) //maximum connections listening to 10 { printf("[SERVER] FAILED TO ESTABLISH LISTENING \n\n"); } printf("[SERVER] Waiting fo client to connect....\n" ); while((connectionSocket=accept(listenSocket , (struct sockaddr*)NULL,NULL))<0); printf("[CONNECTED]\n"); bzero(buffer,1024); if(recv(connectionSocket,buffer,1024,0)<0) printf("ERROR while reading from Client\n"); printf("Message from Client: %s\n",buffer ); switch(buffer[0]) { case 'd': sscanf(buffer+2, "%s", filename); if (buffer[1]=='t') { FILE *fp = fopen(filename, "rb"); bzero(buffer,1024); if (fp>=0) { buffer[0]='x'; stat(filename, &obj); long long int size = (long long) obj.st_size; sprintf(buffer+1, "%lld", size); send(connectionSocket,buffer,1024,0); } printf("The size of file is: %s\n", buffer); while (fread(buffer, sizeof(char), 1024, fp)) { send(connectionSocket,buffer,1024,0); bzero(buffer,1024); } } else if (buffer[1]=='u') { // if (!initUDPServer(filename)) // break; initUDPServer(filename); } break; case 'u': sscanf(buffer+2, "%s", filename); if (buffer[1]=='t'){ sscanf(buffer, "%s", filename); initCDTCP(filename); } else if (buffer[1]=='u') { if (!initUDPClient(filename)) break; } break; } close(connectionSocket); initServer(); }
int main(int argc, char *argv[]) { int serv_pid = 0; int udpServ_pid = 0; int i; char cmd[1024]; char *vals[49]; serv_pid = fork(); if (serv_pid == 0) { listenSocket = socket(AF_INET,SOCK_STREAM,0); if(listenSocket<0) { printf("ERROR WHILE CREATING A SOCKET\n"); } else printf("[SERVER] SOCKET ESTABLISHED SUCCESSFULLY\n\n"); initServer(); close(listenSocket); } char filename[50]; char * returncode; while (1) { printf("$> "); scanf("%[^\n]s", cmd); getchar(); parse(cmd, vals); if(!strcmp(vals[0], "FileDownload")) { if (!strcmp(vals[1], "TCP")) { bzero(filename, 50); cpy(filename+2, vals[2]); filename[0] = 'd'; filename[1] = 't'; if(!initCDTCP(filename)) break; } else if (!strcmp(vals[1], "UDP")) { bzero(filename, 50); cpy(filename+2, vals[2]); filename[0] = 'd'; filename[1] = 'u'; sendMsg(filename); if (!initUDPClient(filename+2)) break; bzero(filename, 50); } } else if (!strcmp(vals[0], "FileUpload")) { if (!strcmp(vals[1], "TCP")) { printf("DOING!!\n\n"); bzero(filename, 50); cpy(filename+2, vals[2]); filename[0] = 'u'; filename[1] = 't'; sendMsg(filename); bzero(filename, 50); } else if (!strcmp(vals[1], "UDP")) { bzero(filename, 50); cpy(filename+2, vals[2]); filename[0] = 'u'; filename[1] = 'u'; sendMsg(filename); initUDPServer(filename+2); bzero(filename, 50); } } else if(!strcmp(vals[0], "exit")) { close(listenSocket); exit(0); } else if(!strcmp(vals[0], "IndexGet")) { // handleIndex(1,0); if (!strcmp(vals[1], "--shortlist")) { handleIndex(0,0,"\0"); } else if (!strcmp(vals[1], "--longlist")) { handleIndex(1,0,"\0"); } else if (!strcmp(vals[1], "--regex")) { handleIndex(1,1,vals[2]); } } continue; } printf("\nClosing connection2\n"); return 0; }