Mercurial > hg > beaglert
view core/UdpServer.cpp @ 53:6907e2177eb8 ultra-staging
Fixed bugs in Udp classes, updated tests
author | Giulio Moro <giuliomoro@yahoo.it> |
---|---|
date | Sun, 07 Jun 2015 14:58:34 +0100 |
parents | f5b5c648cd5d |
children | d3f869b98147 |
line wrap: on
line source
/* * udpServer.cpp * * Created on: 19 May 2015 * Author: giulio moro */ #include "../include/UdpServer.h" UdpServer::UdpServer(int aPort){ init(aPort); }; UdpServer::UdpServer(){ init(0); } UdpServer::~UdpServer(){ }; bool UdpServer::init(int aPort){ enabled=true; stTimeOut.tv_sec = 0; //set timeout to 0 stTimeOut.tv_usec = 0; inSocket=socket(AF_INET, SOCK_DGRAM, 0); if (inSocket < 0){ enabled=false; } length = sizeof(server); server.sin_family=AF_INET; server.sin_addr.s_addr=INADDR_ANY; enabled=bindToPort(aPort); wasteBufferSize=2048; wasteBuffer=malloc(wasteBufferSize); return enabled; } bool UdpServer::bindToPort(int aPort){ port=aPort; if(port<1){ enabled=false; return false; } server.sin_port=htons(port); if (bind(inSocket,(struct sockaddr *)&server,length)<0){ enabled=false; return false; } enabled=true; return true; }; int UdpServer::read(//Returns the number of bytes read, or -1 if there was an error. void *destBuffer, int maxBytesToRead){ if(enabled==false) return -1; FD_ZERO(&stReadFDS); FD_SET(inSocket, &stReadFDS); int descriptorReady= select(inSocket+1, &stReadFDS, NULL, NULL, &stTimeOut); if(descriptorReady<0){ //an error occurred return -1; } int numberOfBytes=0; if (FD_ISSET(inSocket, &stReadFDS)) { numberOfBytes=recvfrom(inSocket,destBuffer,maxBytesToRead,0,(struct sockaddr *)&from,&fromLength); if(numberOfBytes<0) return -1; } return numberOfBytes; }; int UdpServer::emptySocket(){ return emptySocket(0); } int UdpServer::emptySocket(int maxBytes){//discards up to maxBytes from the socket. Returns the number of bytes discarded. if(wasteBuffer==NULL) return -1; int numberOfBytes=0; while(int n=read(wasteBuffer, wasteBufferSize)){// calls the read function until it does not return any more bytes (i.e.: socket is empty) if(n>0) numberOfBytes+=n; if(n<0) return -1; if(maxBytes>0 && numberOfBytes>=maxBytes) break; }; return numberOfBytes; } void* UdpServer::getWaste(){ //returns the last datagram retrieved by emptySocket() return wasteBuffer; }