void run() { try { ndn::Data dataPacket = createDataPacket(); if (m_isForceDataSet) { m_face.put(dataPacket); m_isDataSent = true; } else { m_face.setInterestFilter(m_prefixName, bind(&NdnTlvPoke::onInterest, this, _1, _2, dataPacket), ndn::RegisterPrefixSuccessCallback(), bind(&NdnTlvPoke::onRegisterFailed, this, _1, _2)); } if (m_timeout < ndn::time::milliseconds::zero()) m_face.processEvents(getDefaultTimeout()); else m_face.processEvents(m_timeout); } catch (std::exception& e) { std::cerr << "ERROR: " << e.what() << "\n" << std::endl; exit(1); } }
/*Initial state of receiver side*/ void B_Initial_State(struct pkt packet) { struct msg message; createMessageforLayer5(&packet,&message); bool corrupt = isPacketCorrupt(packet.checksum,packet.seqnum,packet.acknum,message.data); int seqnum = packet.seqnum; struct pkt datapacket; //creating packet containing acknowledgment int checksum=0; if(!corrupt && seqnum==expectedSeqNum) { int ack=expectedSeqNum; //send ack for received packet createDataPacket(&datapacket,0,ack,checksum,""); createCheckSum(&datapacket); //set checksum datapacket.acknum = expectedSeqNum; //re assigning value for correctness tolayer3(B,datapacket); tolayer5(B,message.data); int i; for(i=0;i<20;i++) { printf("%c",message.data[i]); } printf("\n"); //printf("\nB SIDE : Printing Packet payload Sent Above %s\n",message.data); //printf("\nB SIDE : Printing Acknum %d sent from B to A \n",datapacket.acknum); //incrementing the expected sequence number expectedSeqNum++; } else //send previous acknowledgment { int ack =expectedSeqNum-1; createDataPacket(&datapacket,0,ack,checksum,""); createCheckSum(&datapacket); //set checksum datapacket.acknum = expectedSeqNum-1; //reassign for correctness tolayer3(B,datapacket); } }
int main(void) { u32 Data; u32 InData; int Status; volatile int Delay; char test_vect_idx =0; char charidx = 0; u8 DataWrittenDone = 0; char curchar; init_platform(); /* * Initialize the GPIO driver */ Status = XGpio_Initialize(&Gpio, GPIO_EXAMPLE_DEVICE_ID); if (Status != XST_SUCCESS) { return XST_FAILURE; } for (test_vect_idx=0;test_vect_idx<num_test_vectors;test_vect_idx++) { for (charidx=0;charidx<64;charidx++) { curchar = testvector[test_vect_idx][charidx]; //Read the current character Data = createDataPacket(curchar,charidx,test_vect_idx); //Send the 'A' character to byte 3 of testvector 1 print("Sending character \n"); XGpio_DiscreteWrite(&Gpio, OUPTPUT_CHANNEL, Data); //Write into the PL //Double check by reading from the PL for (Delay = 0; Delay < LED_DELAY; Delay++); //Wait for a while //Read back the data from the PL side to see its status do { InData = XGpio_DiscreteRead(&Gpio, INPUT_CHANNEL); for (Delay = 0; Delay < LED_DELAY; Delay++); //Wait for a while before recheck } while (InData&(1<<31)); if ((InData&0xFF)==(Data&0xFF)) { print("Correct\n"); } else { print("Incorrect\n"); } XGpio_DiscreteWrite(&Gpio, OUPTPUT_CHANNEL, 0x00000000); //Release the bus immediately for (Delay = 0; Delay < LED_DELAY; Delay++); //Wait for a while } } print("Done sending. Please press the center button to begin..."); cleanup_platform(); return XST_SUCCESS; }
int create_packets_send() { int i, timeout = 0; printf("llwrite: sending cp1!\n"); while (timeout < ll.numTransmissions) { strcpy(ll.frame,""); strcpy(ctrData.frame,""); createCtrlPackets(0); if(llwrite(2,ctrData.frame,ctrData.sequenceNumber) != 0) printf("llwrite: error sending cp1! Try number %d\n",timeout+1); else break; timeout++; } if(timeout == 3) { printf("llwrite: timed out cp1!\n"); return -1; } for(i = 1; i <= fileData.numSeg; i++) { strcpy(ll.frame,""); strcpy(fileData.frame,""); createDataPacket(i); timeout=0; while (timeout < ll.numTransmissions) { if(llwrite(2,fileData.frame, fileData.sequenceNumber) != 0) printf("llwrite: error sending dataFrame! Try number %d\n",timeout+1); else break; timeout++; } if(timeout == 3) { printf("llwrite: timed out data sending!\n"); return -1; } } printf("llwrite: sending cp2!\n"); timeout=0; while (timeout < ll.numTransmissions) { strcpy(ctrData.frame,""); strcpy(ll.frame,""); createCtrlPackets(1); if(llwrite(2, ctrData.frame, ctrData.sequenceNumber) != 0) printf("llwrite: error sending cp2! Try number %d\n",timeout+1); else break; timeout++; } if(timeout == 3) { printf("llwrite: timed out cp2!\n"); return -1; } return 0; }
void rel_read (rel_t *s) { int numPacketsInWindow = s->LAST_PACKET_SENT - s->LAST_PACKET_ACKED; fprintf(stderr, "REL_READ -- lastpacketsent: %d, lastacked: %d\n", s->LAST_PACKET_SENT, s->LAST_PACKET_ACKED); if (numPacketsInWindow == 0 && s->eofSent == 1 && s->eofRecv == 1) { rel_destroy(s); return; } if (numPacketsInWindow >= s->windowSize || s->eofSent) { // don't send, window's full, waiting for acks return; } // can send packet char payloadBuffer[MAX_PAYLOAD_SIZE]; int bytesReceived = conn_input(s->c, payloadBuffer, MAX_PAYLOAD_SIZE); if (bytesReceived == 0) { return; // no data is available at the moment, just return } else if (bytesReceived == -1) { // eof or error s->eofSent = 1; bytesReceived = 0; // Why do we need to create and send a packet here? // packet_t *packet = createDataPacket(s, payloadBuffer, bytesReceived); // conn_sendpkt(s->c, packet, HEADER_SIZE + bytesReceived); // free(packet); // return; } // TODO: Need to handle overflow bytes here as well packet_t *packet = createDataPacket(s, payloadBuffer, bytesReceived); s->LAST_PACKET_SENT++; fprintf(stderr, "Sent sequence number: %d\n", ntohl(packet->seqno)); conn_sendpkt(s->c, packet, HEADER_SIZE + bytesReceived); // Save packet until it's acked/in case it needs to be retransmitted int slot = s->LAST_PACKET_SENT - s->LAST_PACKET_ACKED - 1; // fprintf(stderr, "Slot: %d\n", slot); memcpy(s->sentPackets[slot]->packet, packet, HEADER_SIZE + bytesReceived); s->sentPackets[slot]->sentTime = getCurrentTime(); s->sentPackets[slot]->acked = 1; fprintf(stderr, "%s\n", "====================SENDING PACKET================"); // fprintf(stderr, "Packet data: %s\n", packet->data); free(packet); }
/*Initial state of receiver side*/ void B_Initial_State(struct pkt packet) { struct msg message; createMessageforLayer5(&packet, &message); bool corrupt = isPacketCorrupt(packet.checksum, packet.seqnum, packet.acknum, message.data); int seqnum = packet.seqnum; struct pkt datapacket; //creating packet containing acknowledgment int checksum = 0; if (!corrupt) { //send ack for all packets lying under below range if (seqnum >= (receiverBase - receiverWindowSize) && seqnum <= (receiverBase + receiverWindowSize - 1)) { int ack = seqnum; //send ack for received packet createDataPacket(&datapacket, 0, ack, checksum, ""); createCheckSum(&datapacket); //set checksum datapacket.acknum = seqnum; //re assigning value for correctness tolayer3(B, datapacket); //this is done irrespective of any action //printf("\nB SIDE : Printing Acknum %d sent from B to A \n", // datapacket.acknum); B_StoreMessageInReceiverBuffer(seqnum, &message); //marks AckSent as true } //for values lying under current window if (seqnum >= receiverBase && seqnum <= (receiverBase + receiverWindowSize - 1)) { /* Handling data sent to layer5*/ int returnVal = returnNextMaximumContiguousSequenceAcknowledged(B); if (returnVal != -1) { sendMessagestoLayer5(returnVal); } } } //Un_corrupt packet Loop Ends }
/*Initial State of Sender Side*/ void A_StorePacketInBuffer(char *message) { struct pkt datapacket; int checksum = 0; createDataPacket(&datapacket, senderPacketCounter, 0, checksum, message); createCheckSum(&datapacket); //modify checksum datapacket.seqnum = senderPacketCounter; //store packet in common senderBuffer for re-sending/sending memcpy(&senderBuffer[senderPacketCounter], &datapacket, sizeof(datapacket)); /*printf( "\nPrinting value is senderBuffer, SeqNum : %d\t checksum : %d\t and payload : %s\n", senderBuffer[senderPacketCounter].seqnum, senderBuffer[senderPacketCounter].checksum, senderBuffer[senderPacketCounter].payload);*/ //increment sender packet counter senderPacketCounter++; }
/* If the reliable program is running in the receiver mode (see c.sender_receiver in rlib.c, you can get its value in rel_create), this receiver should send an EOF to the sender when rel_read is first called. After this first call, the function rel_read can simply return for later calls. Note that this EOF will wait in the receiver's sending window. When timeout happens, the receiver have to retransmit this EOF as well until an ACK is received. If the reliable is running in the sender mode, the rel_read's behavior is the same as that is described above in 3a. */ void rel_read (rel_t *s) { // printf("rel_read\n"); if(s->c->sender_receiver == RECEIVER) { // if already sent eof to the sender/not first call // return; if(s->eofSent == 1) { // fprintf(stderr, "%s\n", "EOF already sent in rel_read"); // s->eofSent = 0; return; } else { // first call // set eofSent to 1 s->eofSent = 1; // send eof char payloadBuffer[MAX_PAYLOAD_SIZE]; int bytesReceived = 0; packet_t *packet = createDataPacket(s, payloadBuffer, bytesReceived); conn_sendpkt(s->c, packet, HEADER_SIZE + bytesReceived); free(packet); // printf("Sending EOF to sender in rel_read\n"); } //if already sent EOF to the sender // return; //else // send EOF to the sender } else //run in the sender mode { //same logic as lab 1 int numPacketsInWindow = s->LAST_PACKET_SENT - s->LAST_PACKET_ACKED; // fprintf(stderr, "REL_READ -- lastpacketsent: %d, lastacked: %d\n", s->LAST_PACKET_SENT, s->LAST_PACKET_ACKED); // fprintf(stderr, "relread -- numPackets: %d, eofRecv: %d, eofSend: %d\n", numPacketsInWindow, s->eofRecv, s->eofSent); if (numPacketsInWindow == 0 && s->eofSent == 1 && s->eofRecv == 1) { rel_destroy(s); return; } if (numPacketsInWindow >= s->windowSize || s->eofSent) { // don't send, window's full, waiting for acks return; } // can send packet char payloadBuffer[MAX_PAYLOAD_SIZE]; memset(payloadBuffer, 0, MAX_PAYLOAD_SIZE); int bytesReceived = conn_input(s->c, payloadBuffer, MAX_PAYLOAD_SIZE); // fprintf(stderr, "Bytes received: %d\n", bytesReceived ); if (bytesReceived == 0) { return; // no data is available at the moment, just return } else if (bytesReceived == -1) { // eof or error s->eofSent = 1; bytesReceived = 0; // Why do we need to create and send a packet here? // packet_t *packet = createDataPacket(s, payloadBuffer, bytesReceived); // conn_sendpkt(s->c, packet, HEADER_SIZE + bytesReceived); // free(packet); // return; } // TODO: Need to handle overflow bytes here as well packet_t *packet = createDataPacket(s, payloadBuffer, bytesReceived); s->LAST_PACKET_SENT++; // fprintf(stderr, "Sent sequence number: %d\n", ntohl(packet->seqno)); // fprintf(stderr, "PACKET INFO: %s\n", packet->data); // fprintf(stderr, "PACKET INFO: %s\n", strdup(payloadBuffer)); // fprintf(stderr, "String Compare Value: %d\n", strcmp(packet->data, "")); conn_sendpkt(s->c, packet, HEADER_SIZE + bytesReceived); // Save packet until it's acked/in case it needs to be retransmitted int slot = s->LAST_PACKET_SENT - s->LAST_PACKET_ACKED - 1; // fprintf(stderr, "Slot: %d\n", slot); memcpy(s->sentPackets[slot]->packet, packet, HEADER_SIZE + bytesReceived); s->sentPackets[slot]->sentTime = getCurrentTime(); s->sentPackets[slot]->acked = 1; // fprintf(stderr, "%s\n", "====================SENDING PACKET================"); // fprintf(stderr, "Packet data: %s\n", packet->data); free(packet); } }
int sendFile(unsigned char* file, size_t fileSize, char* fileName) { if(fileSize > MAX_FILESIZE_ALLOWED) { printf("This file is too large to be sent!\n"); return -1; } if(strlen(fileName) > (applicationLayerConf.maxPacketSize - (BASE_DATA_PACKET_SIZE + sizeof(size_t)) ) || strlen(fileName) > 255) { printf("The filename is too large!\n"); return -1; } size_t startPacketSize; unsigned char* startPacket = createControlPacket(&startPacketSize, CONTROL_START, fileSize, fileName); size_t endPacketSize; unsigned char* endPacket = createControlPacket(&endPacketSize, CONTROL_END, fileSize, fileName); unsigned int sizeDone = 0; //Calculate the number of packets we will need based on the defined maximum packet size unsigned long numberOfPackets = fileSize / applicationLayerConf.maxDataFieldSize; //Checks the remainder of previous division to check if we need an extra packet or not if((fileSize % applicationLayerConf.maxDataFieldSize) > 0) numberOfPackets++; if(sendData(startPacket, startPacketSize) == -1) { free(startPacket); return -1; } free(startPacket); unsigned long currentPacket = 0; unsigned long currentSequence = 0; loadBar(currentPacket, numberOfPackets, numberOfPackets, 50, sizeDone, fileSize); for(; currentPacket < numberOfPackets; currentPacket++) { unsigned long dataFieldSize; if(currentPacket == numberOfPackets - 1) { //We do this to ensure we don't copy more than the needed bytes in the last packet dataFieldSize = fileSize - currentPacket * applicationLayerConf.maxDataFieldSize; } else dataFieldSize = applicationLayerConf.maxDataFieldSize; sizeDone += dataFieldSize; unsigned char dataField[applicationLayerConf.maxDataFieldSize]; memcpy(dataField, &file[currentPacket * applicationLayerConf.maxDataFieldSize], dataFieldSize); unsigned char* dataPacket = createDataPacket(currentPacket, dataFieldSize, dataField); if(sendData(dataPacket, dataFieldSize + BASE_DATA_PACKET_SIZE) == -1) { free(dataPacket); return -1; } free(dataPacket); if(currentSequence > 255) currentSequence = 0; else currentSequence++; loadBar(currentPacket+1, numberOfPackets, numberOfPackets, 50, sizeDone, fileSize); } if(sendData(endPacket, endPacketSize) == -1) { free(endPacket); return -1; } printf("\n\n"); free(endPacket); return 0; }
void ListenServerNetMode::syncOutgoingPackets(ObjectManager* objectManager) { /** * WARNING: Make sure to always send spawn packets first, and then data packets. Otherwise players may get object * data that belongs to or points to an object that hasn`t been created yet. */ /** Step 1 - handle spawning objects that already exist on active players machines to connected players. */ // So, if there are any new players connected... if(m_connectedPlayers.size() > 0) { // ...go through all replicated objects... for(Object* object : objectManager->xiGetReplicatedObjects()) { // ...if the object exists and has already been spawned on active players machines... if(object && object->riGetRepLayout()->isSpawned) { // ...create a spawn packet and send it to all connected players. if(ENetPacket* packet = createSpawnPacket(object)) { for(SPlayer* player : m_connectedPlayers) { enet_peer_send(player->peer, NETWORK_CHANNEL_ID_DATA, packet); } } } } } /** Step 2 - handle spawning objects that hasn`t been spawned to anyone yet. */ // So, for every object that hasn`t been spawned on any player machine yet... for(Object* object : objectManager->xiGetNewReplicatedObjects()) { // Create a spawn packet and send it to all players. if(ENetPacket* packet = createSpawnPacket(object)) { enet_host_broadcast(m_host, NETWORK_CHANNEL_ID_DATA, packet); } // Mark the object as spawned object->riGetRepLayout()->isSpawned = true; } // Clear new replicated objects container so we don`t constantly send the same spawn packets. objectManager->xiClearNewReplicatedObjects(); /** Step 3 - handle sending initial object data to connected players. */ // So, if there are any new players connected if(m_connectedPlayers.size() > 0) { // ...go through all replicated objects... for(Object* object : objectManager->xiGetReplicatedObjects()) { // ...if the object exists... if(object) { // ...create a initial data packet and send it to all connected players. if(ENetPacket* packet = createDataPacket(object, true)) { for(SPlayer* player : m_connectedPlayers) { enet_peer_send(player->peer, NETWORK_CHANNEL_ID_DATA, packet); } } } } } /** Step 4 - handle sending delta object data to active players. */ // So, for every replicated object (both new and old ones)... for(Object* object : objectManager->xiGetReplicatedObjects()) { // ...if the object exists... if(object) { // ...create a data packet and send it to active players if any data has to be sent if(ENetPacket* packet = createDataPacket(object, true)) { for(SPlayer* player : m_activePlayers) { enet_peer_send(player->peer, NETWORK_CHANNEL_ID_DATA, packet); } } } } }
/* * Connect to the host and read/write a file */ int initClient(char *hostname, int port, char *filename) { struct hostent *he; printf("\tResolving hostname: %s\n", hostname); if ((he=gethostbyname(hostname)) == NULL) { perror("Error resolving hostname"); return 1; } printf("\tInitialising socket on port %d\n", port); if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("Error initialising socket."); return 1; } server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); server_addr.sin_addr = *((struct in_addr*)he->h_addr); memset(&(server_addr.sin_zero), '\0', 8); struct timeval tv; tv.tv_sec = 10; /* 10 Secs Timeout */ tv.tv_usec = 0; // Not init'ing this can cause strange errors setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,sizeof(struct timeval)); // create a thread listening for packets pthread_t listener_thread; pthread_create(&listener_thread, NULL, (void*(*)(void*))listenForPackets, NULL); if (isReadMode) { printf("\tSending read request for file: %s\n", filename); struct packet *p; if ((p = createReadWritePacket(1, filename)) == NULL) { printf("\tError creating packet."); } else { int i; for (i = 0; ; i++) { if (i == 4) { printf("\tTransfer timed out.\n"); exit(1); } // send RRQ sendPacket(p->buffer, p->bufferLen, sockfd, (struct sockaddr *)&server_addr); usleep(1000000); if (receivedERROR) { printf("\tError code %d: %s\n", packet[1], getData(packet, numbytes)); exit(1); } if (receivedACK) { receivedACK = 0; break; } } int dataBlock = 1; FILE *fp = fopen(filename, "wb"); if (fp != NULL) { for (i = 0; ; i++) { if (receivedDATA) { receivedDATA = 0; // write data char *theData = getData(packet, numbytes); fwrite(theData, sizeof(char), numbytes-4, fp); // send ACK for (i = 0; ; i++) { if (i == 4) { printf("\tTransfer timed out.\n"); exit(1); } struct packet *ack = createACKPacket(dataBlock); sendPacket(ack->buffer, ack->bufferLen, sockfd, (struct sockaddr*)&server_addr); usleep(1000000); if (receivedERROR) { printf("\tError code %d: %s\n", packet[1], getData(packet, numbytes)); exit(1); } if (receivedDATA) { receivedDATA = 0; dataBlock++; break; } if (numbytes < 512) exit(1); } } } fclose(fp); } else { printf("Error code 0: unable to open/read file.\n"); exit(1); } } } else if (isWriteMode) { printf("\tSending write request for file: %s\n", filename); struct packet *p; if ((p = createReadWritePacket(2, filename)) == NULL) { printf("\tError creating packet."); } else { // send WRQ int i; for (i = 0; ; i++) { if (i == 4) { printf("\tTransfer timed out.\n"); exit(1); } // send RRQ sendPacket(p->buffer, p->bufferLen, sockfd, (struct sockaddr *)&server_addr); usleep(1000000); if (receivedERROR) { printf("\tError code %d: %s\n", packet[1], getData(packet, numbytes)); exit(1); } if (receivedACK) { receivedACK = 0; break; } } // get the file data into a buffer struct packet *f; if ((f = getFileData(filename)) != NULL) { int dataBlock = 1, count = 0; printf("Buffer size: %d\n", f[0].bufferLen); if (f[0].bufferLen <= 0) { printf("\tError code 0: File is of size 0 bytes.\n"); exit(1); } while (dataBlock < f[0].bufferLen) { struct packet *d = createDataPacket(dataBlock, f[dataBlock].buffer); sendPacket(d->buffer, d->bufferLen, sockfd, (struct sockaddr*)&server_addr); // wait for ACK printf("\tWaiting for ACK packet.\n"); int c; for (c = 0; ; c++) { if (c == 8) { break; // resend the data } if (receivedACK) { dataBlock++; break; } usleep(500000); } count++; usleep(1000000); // without this you end up with race conditions because of threads... } } else { printf("\tError code 4: File not found.\n"); exit(1); } } } return 0; }