QByteArray encodeData(const T1 &a1, const T2 &a2)
{
    const int a2Offset = getValueEncodedSize(a1);
    const int size = a2Offset + getValueEncodedSize(a2);
    QByteArray result(size, Qt::Uninitialized);
    packData(result.data(), a1);
    packData(result.data() + a2Offset, a2);
    return result;
}
Esempio n. 2
0
int Log::serialize(void* const data)
{
	#ifdef DEBUG_OUT
	printf("Log::serialize(void* const data)\n");
	#endif //DEBUG_OUT
	MEMUNIT* data2 = (MEMUNIT*)data;
	packNData(data2, this->log, LOG_MESSAGE_SIZE);
	packNData(data2, this->sourceID, ID_SIZE);
	packNData(data2, this->uniqueSourceID, UNIQUEID_SIZE);
	packData(data2, this->level);
	packData(data2, this->logtime);

	return this->getSerializedSize();
}
QByteArray encodeData(const T1 &a1, const T2 &a2, const T3 &a3, const T4 &a4, const T5 &a5)
{
    const int a2Offset = getValueEncodedSize(a1);
    const int a3Offset = a2Offset + getValueEncodedSize(a2);
    const int a4Offset = a3Offset + getValueEncodedSize(a3);
    const int a5Offset = a4Offset + getValueEncodedSize(a4);
    const int size = a5Offset + getValueEncodedSize(a5);
    QByteArray result(size, Qt::Uninitialized);
    packData(result.data(), a1);
    packData(result.data() + a2Offset, a2);
    packData(result.data() + a3Offset, a3);
    packData(result.data() + a4Offset, a4);
    packData(result.data() + a5Offset, a5);
    return result;
}
Esempio n. 4
0
	void loadAssets()
	{
		log("loading profiles", "LoadAssets"); 	loadProfiles();

		for(string packPath : getScan<Mode::Single, Type::Folder>("Packs/"))
		{
			string packName{packPath.substr(6, packPath.length() - 6)};

			string packLua{""};
			for(const auto& path : getScan<Mode::Recurse, Type::File, Pick::ByExt>(packPath, ".lua")) packLua.append(getFileContents(path));
			string packHash{Online::getMD5Hash(packLua + HG_SKEY1 + HG_SKEY2 + HG_SKEY3)};

			Json::Value packRoot{getRootFromFile(packPath + "/pack.json")};
			PackData packData(packName, packRoot["name"].asString(), packRoot["priority"].asFloat(), packHash);
			packDataMap.insert(make_pair(packName, packData));
		}

		vector<PackData> packDatasToQuery;
		for(pair<string, PackData> packDataPair : packDataMap) packDatasToQuery.push_back(packDataPair.second);
		sort(begin(packDatasToQuery), end(packDatasToQuery), [](PackData a, PackData b) { return a.getPriority() < b.getPriority(); });

		for(PackData packData : packDatasToQuery)
		{
			string packName{packData.getId()}, packPath{"Packs/" + packName + "/"};
			packPaths.push_back("Packs/" + packName + "/");
			log("loading " + packName + " music", "LoadAssets");			loadMusic(packPath);
			log("loading " + packName + " music data", "LoadAssets");		loadMusicData(packPath);
			log("loading " + packName + " style data", "LoadAssets");		loadStyleData(packPath);
			log("loading " + packName + " level data", "LoadAssets");		loadLevelData(packPath);
			log("loading " + packName + " events", "LoadAssets");			loadEvents(packPath);
			log("loading " + packName + " custom sounds", "LoadAssets");	loadCustomSounds(packName, packPath);
		}
	}
void forwardQuery(char *commandName, unsigned int key, unsigned int value, unsigned long responseAddress, unsigned int responsePort) {	
	int requestId = searchRequestId(key, responseAddress, responsePort);
	if (requestId == -1) { // not ours
		forceForwardQuery(commandName, key, value, responseAddress, responsePort);
	} else {
		convertToClientCommand(commandName);
		
		struct client_request request = openClientRequests[requestId];
		request.active = 0;
		openClientRequests[requestId] = request;
		
		unsigned char buffer[CLIENT_BUFFER_LENGTH];
		int sockfd;
		
		if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
			printf("Socket not created!");
			exit(1);
		}
		
		packData(buffer, commandName, key, value);
		printf("RETURN> [%s] %d:%d (back to: %lu:%d, using cached socket)\n", commandName, key, value, responseAddress, responsePort);
		if(sendto(sockfd, buffer, sizeof(buffer), 0, (&request.socket), successor_addrlen) < 0){ // todo: addr_len dafuck?
			printf("FATAL: sending error.");
		}
		close(sockfd);
	}
	printf("Complete.\n\n");
	return;
}
QByteArray encodeData(const T1 &a1)
{
    const int size = getValueEncodedSize(a1);
    QByteArray result(size, Qt::Uninitialized);
    packData(result.data(), a1);
    return result;
}
Esempio n. 7
0
void MadsM4Engine::dumpFile(const char* filename, bool uncompress) {
	Common::DumpFile f;
	byte buffer[DUMP_BUFFER_SIZE];
	Common::SeekableReadStream *fileS = res()->get(filename);
	
	if (!f.open(filename))
		error("Could not open '%s' for writing", filename);

	int bytesRead = 0;
	warning("Dumping %s, size: %i\n", filename, fileS->size());

	if (!uncompress) {
		while (!fileS->eos()) {
			bytesRead = fileS->read(buffer, DUMP_BUFFER_SIZE);
			f.write(buffer, bytesRead);
		}
	} else {
		MadsPack packData(fileS);
		Common::SeekableReadStream *sourceUnc;
		for (int i = 0; i < packData.getCount(); i++) {
			sourceUnc = packData.getItemStream(i);
			debugCN(kDebugCore, "Dumping compressed chunk %i of %i, size is %i\n", i + 1, packData.getCount(), sourceUnc->size());
			while (!sourceUnc->eos()) {
				bytesRead = sourceUnc->read(buffer, DUMP_BUFFER_SIZE);
				f.write(buffer, bytesRead);
			}
			delete sourceUnc;
		}
	}

	f.close();
	res()->toss(filename);
	res()->purge();
}
void NxLine::addPoint(const Nx::Vector3 &p, const NxColourValue & Col )
{
	mPoints.push_back(p);
	if(mUseVertexColour){ mPointsColor.push_back( packData( Col )); } 
	mDirty = true;

	mAnimSpline->addPoint(  NxVec3ToOgre( p ) );
}
void NxLine::setPointColour( unsigned short index, const NxColourValue &Value )
{
	assert(index < mPointsColor.size() && "Point index is out of bounds!!");
	if(mUseVertexColour){
		mPointsColor[index] = packData( Value );
		mDirty = true;
	} 
}
int packDataForInternal(unsigned char *buffer, char *commandName, unsigned int key, unsigned int value, unsigned long responseAddress, unsigned int responsePort) {
	packData(buffer, commandName, key, value);
	buffer[8] = responseAddress >> 24;
	buffer[9] = responseAddress >> 16;
	buffer[10] = responseAddress >> 8;
	buffer[11] = responseAddress;
	buffer[12] = responsePort >> 8;
	buffer[13] = responsePort;
}
Esempio n. 11
0
void NxLine::addPoint(float x, float y, float z, const NxColourValue & Col )
{
	mPoints.push_back(Nx::Vector3(x,y,z));
	if(mUseVertexColour){ mPointsColor.push_back( packData( Col )); } 
	mDirty = true;

	mAnimSpline->addPoint(Vector3(x,y,z));

}
Esempio n. 12
0
int main(int argc, char *argv[])
{
    int sockfd;
    struct sockaddr_in their_addr; // connector's address information
    struct hostent *he;
    int numbytes;
    int serverPort;
    int a = 0;
    int b = 0;

    printf("TCP client example\n\n");
    
    if (argc != 5) {
        fprintf(stderr,"Usage: tcpClient serverName serverPort int1 int2\n");
        exit(1);
    }
    
    serverPort = atoi(argv[2]);
    a = atoi(argv[3]);
    b = atoi(argv[4]);    

    //Resolv hostname to IP Address
    if ((he=gethostbyname(argv[1])) == NULL) {  // get the host info
        herror("gethostbyname");
        exit(1);
    }

    /* ******************************************************************
    TO BE DONE: Create socket
    ******************************************************************* */


    //setup transport address
    their_addr.sin_family = AF_INET;     
    their_addr.sin_port = htons(serverPort);
    their_addr.sin_addr = *((struct in_addr *)he->h_addr);
    memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero);


    /* ******************************************************************
    TO BE DONE:  Binding
    ******************************************************************* */
    
    unsigned char buffer[4];

    packData(&buffer, a, b);

    /* ******************************************************************
    TO BE DONE:  Send data
    ******************************************************************* */

    /* ******************************************************************
    TO BE DONE:  Close socket
    ******************************************************************* */

    return 0;
}
Esempio n. 13
0
int Telegram::serialize(void* const data)
{
	//void* data = malloc(this->getSerializedSize());
	#ifdef DEBUG_OUT
	printf("in Telegram::serialize(void* const data)\n");
	#endif //DEBUG_OUT
	MEMUNIT* data2 = (MEMUNIT*)data;
	packNData(data2, this->destinationID, UNIQUEID_SIZE);
	packNData(data2, this->sourceID, UNIQUEID_SIZE);
	packData(data2, this->type);
	//packData(data2, this->telegramSize);
	packData(data2, this->uniqueDestination);

	#ifdef DEBUG_OUT
	printf("Offset data2 %p to data %p\n", data2, data);
	#endif //DEBUG_OUT

	return Telegram::getSerializedSize();
}
Esempio n. 14
0
void packLongData(char *output, const QByteArray &value)
{
    const quint32 sizeToWrite = quint32((value.size() << 8) + 0xfe);
    packData(output, sizeToWrite);
    output += 4;
    writeData(output, value.data(), value.size());
    output += value.size();
    int extraBytes = value.size() & 3;
    if (extraBytes) {
        writeData(output, s_nulls, 4 - extraBytes);
    }
}
Esempio n. 15
0
//Remove element from Hashtable
int removeElement(int key){
    //Build buffer and initialize it 
    unsigned char buffer[BUFSIZE];
    packData(buffer,"DEL",key,0);

    //Send that data to server
    sendMessage(buffer);

    //Receive awnser
    receiveMessage(buffer);

    //Return if methof ran successful
    return (buffer[0] =='O');
}
Esempio n. 16
0
//Add element to Hashtable
int set(int key, int value){
    //Build buffer and initialize it 
    unsigned char buffer[BUFSIZE];
    packData(buffer,"SET",key,value);

    //Send that data to server
    sendMessage(buffer);

    //Receive awnser
    receiveMessage(buffer);

    //Return if methof ran successful
    return (buffer[0] =='O');
}
Esempio n. 17
0
extern "C" int main(void)
{
	//state == 0: IDLE wait for scan start signal
	//state == 1: INITIATE SCAN: reset all data and start new scan
	//state == 2; scanning... transmitting data
	//state == 3: scan complete cleanup and reset to state 0
	int state = STATEIDLE;

	//Main loop
	while(1){
		//IDLE
		//Wait for command to start scanning
		if (state == STATEIDLE){
			if(checkIncomingCmd() == 1){
				if(checkPCCmd() == 1){
					sendPCStart();
					state = STATEINITIATE;
				}
			}
		//INITIATE
		}else if(state == STATEINITIATE){
			resetState();
			state = STATESCAN;
		//SCANNING
		}else if (state == STATESCAN){
			if(checkIncomingCmd() == 1){
				if(checkPCCmd() == 1){
					sendPCStart();
					state = STATEINITIATE;
				}
			}
			if(packData() == 1){
				usb_rawhid_send(data_out, 15);
			}
			if(rotation == MAXROTATION){
				state = STATEEND; 
			}
		//scan complete cleanup and reset to state 0
		}else if (state == STATEEND){
			resetState();
			sendPCEnd();
			state = STATEIDLE;
		}//STATEEND
	}//main loop
}//main
Esempio n. 18
0
//Get element from Hashtable
int get(int key, int* error){
    //Build buffer and initialize it 
    unsigned char buffer[BUFSIZE];
    packData(buffer,"GET",key,0);

    //Send that data to server
    sendMessage(buffer);

    //Receive awnser
    receiveMessage(buffer);

    //Unpack data
    char command[4];
    int a,b;
    unpackData(buffer,command,&a,&b);
    
    //Check if problem rann correctly
    *error = buffer[0] == 'V';    

    //Return if methof ran successful
    return b;
}
Esempio n. 19
0
int main(int argc, char *argv[])
{
    int sockfd;
    struct sockaddr_in their_addr; // connector's address information
    struct hostent *he;
    int numbytes;
    int serverPort;
    int a = 0;
    int b = 0;
	struct timespec tStart,tEnd;

    printf("TCP client example\n\n");
    
    if (argc != 5) {
        fprintf(stderr,"Usage: tcpClient serverName serverPort int1 int2\n");
        exit(1);
    }
    
    serverPort = atoi(argv[2]);
    a = atoi(argv[3]);
    b = atoi(argv[4]);    

    //Resolv hostname to IP Address
    if ((he=gethostbyname(argv[1])) == NULL) {  // get the host info
        herror("gethostbyname");
        exit(1);
    }

    /* ******************************************************************
    TO BE DONE: Create socket
    ******************************************************************* */
	// starttime (gettime)
	if(clock_gettime(CLOCK_REALTIME, &tStart)!=0) {
        fprintf(stderr,"Could not get starttime \n");
        exit(1);
	}
	printf("Start timestamp: %d \n", (int)tStart.tv_sec);
	
	// create socket
    sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_IP); 


    //setup transport address
    their_addr.sin_family = AF_INET;     
    their_addr.sin_port = htons(serverPort);
    their_addr.sin_addr = *((struct in_addr *)he->h_addr);
    memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero);


    /* ******************************************************************
    TO BE DONE:  Binding
    ******************************************************************* */
	// connect and cast pointer from their_addr
    int connect_return = connect(sockfd, (struct sockaddr *)&their_addr, sizeof their_addr);	//connect() + casten + Testvariable
	
	// small connection notice -> 0 = success
    printf("Connection: %s \n", (connect_return==0) ? "etablished" : "failed");
    
    unsigned char buffer[4];

	//assign length of buffer
    int data_length = packData(&buffer, a, b);			

    /* ******************************************************************
    TO BE DONE:  Send data
    ******************************************************************* */
	
	// send buffer
    int send_return = send(sockfd, &buffer, data_length, 0);
	
	// small send notice
    printf("Send: %d \n", send_return);
		
    /* ******************************************************************
    TO BE DONE:  Close socket
    ******************************************************************* */
	// close connection
    int close_return = close(sockfd);
	
	// endtime (gettime)
	if(clock_gettime(CLOCK_REALTIME, &tEnd)!=0) {
        fprintf(stderr,"Could not get endtime \n");
        exit(1);
	}
	printf("End timestamp: %d \n", (int)tEnd.tv_sec);
		
	// small disconnection notice -> 0 = success
    printf("Closing connection: %s \n", (close_return==0) ? "successfull" : "fail");
    
	// get timedifference
	printf("Used time: %d second(s) and %d nanosecond(s) \n", ((int)tEnd.tv_sec)-((int)tStart.tv_sec), ((int)tEnd.tv_nsec)-((int)tStart.tv_nsec) );

    return 0;
}
Esempio n. 20
0
int main(int argc, char *argv[]) {
	struct sockaddr_in their_addr; // connector's address information
	struct sockaddr_in my_addr; // local address information

	struct hostent *he;
	int numbytes;
	int serverPort;
	unsigned int a = 0;
	unsigned int b = 0;
	unsigned int testa = 0;
	unsigned int testb = 0;
	int socketfd = 0;

	int sendRepeatTimes = 50;

	unsigned char buffer[4];

	printf("TCP client\n\n");

	if (argc != 5) {
		fprintf(stderr, "Usage: tcpClient serverName serverPort int1 int2\n");
		exit(1);
	}

	serverPort = atoi(argv[2]);
	a = (unsigned int) atoi(argv[3]);
	b = (unsigned int) atoi(argv[4]);

	//Resolv hostname to IP Address
	if ((he = gethostbyname(argv[1])) == NULL ) {  // get the host info
		herror("gethostbyname");
		exit(1);
	}
	printf("Arguments server=%s:%i NrA=%i NrB=%i\n", argv[1], serverPort, a, b);

	// create server socket
	socketfd = socket(PF_INET, SOCK_STREAM, 0);

	if (socketfd == -1) {
		fprintf(stderr, "Create Socket: Error %i\n", errno);
	} else {
		//setup transport address
		puts("Create socket!\n");
		their_addr.sin_family = AF_INET;
		their_addr.sin_port = htons(serverPort);
		their_addr.sin_addr = *((struct in_addr *) he->h_addr);
		memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero);

		my_addr.sin_family = AF_INET;
		my_addr.sin_port = htons(LOCAL_PORT);
		my_addr.sin_addr.s_addr = INADDR_ANY;
		memset(my_addr.sin_zero, '\0', sizeof my_addr.sin_zero);

		// bind socket to  local machine
		int yes = 1;

		// reuse socket if already in used
		if (setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int))
				== -1) {
			perror("setsockopt");
			exit(1);
		}

		if (bind(socketfd, (struct sockaddr *) &my_addr, sizeof my_addr)
				== -1) {
			fprintf(stderr, "Bind socket: Error %i\n", errno);
		} else {
			puts("Bind socket!\n");

			packData(&buffer, a, b);
			unpackData(&buffer, &testa, &testb);

			if (testa != a || testb != b) {
				fprintf(stderr, "Pack Data: wrong implementation \n");
			} else {
				puts("Pack data!\n");
			}

			if (connect(socketfd, (struct sockaddr *) &their_addr,
					sizeof their_addr) == -1) {
				fprintf(stderr, "connect to server: Error %i\n", errno);
			} else {
				puts("connected to server!\n");

				while (sendRepeatTimes--) {
					numbytes = send(socketfd, buffer, sizeof buffer, 0);
					if (numbytes == -1) {
						fprintf(stderr, "send: Error %i\n", errno);
					}
					printf("send %i Bytes\n",numbytes);
				}
			}
			close(socketfd);
			puts("close socket!\n");
			puts("tcpClient End\n\n");
		}
	}
	return 0;
}
int main(int argc, char** argv)
{
	unsigned int count = 0;
	roll = pitch = yaw = 0.0;

	if(argc == 1)
	{
		ROS_ERROR("Specify serial port. e.g., /dev/ttyUSB0");
		return -1;
	}

	ros::init(argc, argv, "ar_listener");
	ros::NodeHandle node;
	tf::TransformListener listener;

	// Autopilot control status topic creation
	ros::Publisher control_status = node.advertise<std_msgs::Bool>("isauto",1000);
	 
	// Serial comm related
	int fd;
	struct termios newtio;

	struct pollfd poll_events;
	int poll_state;
	
	// open, we trust a user should enter /dev/ttyS0 or so.
	fd = open(argv[1], O_RDWR | O_NOCTTY | O_NONBLOCK); 

	if (fd <0) 
	{
		ROS_ERROR("Serial port open error %s",argv[1]);
		perror(MODEMDEVICE); 
		exit(-1); 
	}
	else
	{
		ROS_INFO("Connected to %s successfully.",argv[1]);
	}

	bzero(&newtio, sizeof(newtio)); /* clear struct for new port settings */

        /* 
          BAUDRATE: Set bps rate. You could also use cfsetispeed and cfsetospeed.
          CS8     : 8n1 (8bit,no parity,1 stopbit)
          CLOCAL  : local connection, no modem contol
          CREAD   : enable receiving characters
        */
	newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;

        /*
          IGNPAR  : ignore bytes with parity errors
          otherwise make device raw (no other input processing)
        */
         newtio.c_iflag = IGNPAR;
         
        /*
         Raw output.
        */
         newtio.c_oflag = 0;
	newtio.c_lflag = 0;
	newtio.c_cc[VMIN]     = 1;     /* blocking read until 1 character arrives */
	newtio.c_cc[VTIME]    = 0;     /* inter-character timer unused */

	tcflush(fd,TCIFLUSH);
	tcsetattr(fd,TCSANOW,&newtio);

	// Poll for data receiving.
	poll_events.fd = fd;
	poll_events.events = POLLIN | POLLERR;
	poll_events.revents = 0;

	ros::Rate rate(30.0);
	bool success = true;

	while (node.ok())
	{

		poll_state = poll((struct pollfd*)&poll_events,1,0); // immediately return

		std_msgs::Bool isauto;
		tf::StampedTransform transform;
		tf::Quaternion attitude;
		success = true;
		ros::Time now = ros::Time::now();
		
		try
		{
			//listener.waitForTransform("/ar_marker","/pgr_camera_frame",now,ros::Duration(0.033));
			listener.lookupTransform("/ar_marker","/pgr_camera_frame",ros::Time(0),transform);
		}
		catch(tf::TransformException ex)
		{
			//ROS_ERROR("%s",ex.what());
			//write(fd,toHeli,16);
			//ros::spinOnce();
			//rate.sleep();
			//continue;
			success = false;
		}

		ros::Duration d = ros::Time::now() - transform.stamp_;

		if(d.toSec() > 0.5)
		{
			success = false;
		}

		if(success)
		{
			packData(transform.getOrigin().x(),transform.getOrigin().y(),transform.getOrigin().z(),1);
			attitude = transform.getRotation();
			btMatrix3x3(attitude).getRPY(roll,pitch,yaw);
			roll = roll*RAD2DEG;
			pitch = pitch*RAD2DEG;
			yaw = yaw*RAD2DEG;
			ROS_DEBUG("[%06d]:LOC(%f,%f,%f),RPY:(%f,%f,%f)",count++,transform.getOrigin().x(),transform.getOrigin().y(),transform.getOrigin().z(),roll,pitch,yaw);
			
		}
		else
		{
			packData(0.0,0.0,0.0,0);
		}

		if(poll_state > 0)
		{
			if(poll_events.revents & POLLIN)
			{
				int cnt = read(fd,buf,1);
				ROS_DEBUG("Serial received! - %d %x",cnt,buf[0]);
				isauto.data = true;
				control_status.publish(isauto);
			}

			if(poll_events.revents & POLLERR)
			{
				ROS_INFO("Poll error!");
			}
			// res = read(fd,buf,255);
			// See http://www.faqs.org/docs/Linux-HOWTO/Serial-Programming-HOWTO.html
		}


		write(fd,toHeli,PKT_LENGTH);
		ros::spinOnce();
		rate.sleep();
	}

	close(fd);

	return 0;
}
Esempio n. 22
0
void packData(void *output, const QString &value)
{
    packData(output, value.toUtf8());
}
int rpcCall(int cmd, int k, int v)
{
  int sockfd;

  if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    printf("Fatal: Socket not created!");
    return 0;
  }

  // translate cmd id to cmd string
  if(cmd == 0) strcpy(commandName, "set");
  if(cmd == 1) strcpy(commandName, "get");
  if(cmd == 2) strcpy(commandName, "del");


  packData(buffer, commandName, k, v);
  printf("\nSending: %s %d %d\n", commandName, k, v);

  if(sendto(sockfd, buffer, sizeof(buffer), 0, (const struct sockaddr *)&their_addr, addrlen) < 0){
    printf("Fatal: Sending error.\n");
    return 0;
  }
  printf("Send complete. Waiting for response...\n");

  status = 0;
  while(status == 0) {
    status = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&their_addr, &addrlen);
  }

  // mega hardcode hack because their_addr is modified in recvfrom
  their_addr.sin_port = server_port;


  unpackData(buffer, commandName_recv, &key_recv, &value_recv);
  printf("Received: %s %d %d \n", commandName_recv, key_recv, value_recv);

  close(sockfd);

  if(cmd == SET_COMMAND){
    if(isOkQuery(commandName_recv)){
      return 1;
    } else{
      return ERROR;
    }
  } else if(cmd == GET_COMMAND) {
    if(isValueQuery(commandName_recv)){
      return value_recv;
    } else if (isNotFoundQuery(commandName_recv)) {
      return NOT_FOUND;
    } else{
      return ERROR;
    }
  } else if(cmd == DELETE_COMMAND) {
    if (isOkQuery(commandName_recv)) {
      return 0;
    } else if (isNotFoundQuery(commandName_recv)) {
      return NOT_FOUND;
    } else {
      return ERROR;
    }
  }
}
Esempio n. 24
0
int main(int argc, char *argv[]) {
    int sockfd;
    struct sockaddr_in own_addr, client_addr; // connector's address information
    struct hostent *he;
    int udpPort;
    struct timespec t2, t3;

    printf("Server starts \n");

    if (argc != 2) {
        fprintf(stderr,"Usage: udpPort\n");
        exit(1);
    }
	printf("server port reading\n");
    //Port setzen
    udpPort = atoi(argv[1]); //atoi holt aus einem String eine Zahl
	printf("server port is readed\n");	
	printf("server create a socket\n");
	
    //set a udp Server
    sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
    if(sockfd == -1) {
        fprintf(stderr, "Error creating socket DAS HIER????\n");
        return 1;
    }
	printf("Server socked created\n");	

    //Resolv hostname to IP Address
    if ((he=gethostbyname("localhost")) == NULL) { // get the host info
        herror("gethostbyname");
	printf("servername couldn't set");
        exit(1);
    }
	printf("Servername localhost is set");

    own_addr.sin_family = AF_INET;
    own_addr.sin_port = htons(udpPort);
    own_addr.sin_addr = *((struct in_addr *)he->h_addr);

    memset(own_addr.sin_zero, '\0', sizeof own_addr.sin_zero);
    //bind socket
    if(bind(sockfd, (const struct sockaddr*)&own_addr, sizeof(own_addr)) == -1) {
        fprintf(stderr, "Error creating socket\n");
        return 1;
    }

    socklen_t client_addr_size;

    char buffer[20];

    int n;
    while(1) {
		printf("server ist waiting for Request");
        if((n=recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&client_addr, &client_addr_size)) != 20) {
            fprintf(stderr, "Server :::Error receiving data. expected 20 bytes but got %d \n", n);
            return 1;
        }
	 //Zweiter Zeitstempel
        clock_gettime(CLOCK_REALTIME, &t2);
        printf("Request received");
        if(!checkMessage(buffer)) {
            fprintf(stderr, "bad message received");
            return 1;
        }
	if(unpackData(buffer)==false){
		printf("Error, unknown command");
	}
		
       
        //Dritter Zeitstempel
        //don't print but send
        //define command
        packData(buffer, &t2);
        if((n=sendto(sockfd, buffer, 20, 0, (struct sockaddr*)&client_addr, client_addr_size)) != 20) {
            fprintf(stderr, "Error sending back data. expected 20 bytes but got %d \n", n);
            return 1;
        }
        clock_gettime(CLOCK_REALTIME, &t3);
        packData2(buffer, &t2,&t3);
        if((n=sendto(sockfd, buffer, 20, 0, (struct sockaddr*)&client_addr, client_addr_size)) != 20) {
            fprintf(stderr, "Error sending back data. expected 20 bytes but got %d \n", n);
            return 1;
        }
    }

    if( close(sockfd) == -1 ) {
        fprintf(stderr, "Error closing socket.\n");
    }

    return 0;
}