comparison core/UdpServer.cpp @ 44:f5b5c648cd5d ultra-staging

- added (unused) simple c++ classes for udp datagrams\n- added tests for the new classes
author Giulio Moro <giuliomoro@yahoo.it>
date Wed, 20 May 2015 18:07:16 +0100
parents
children 6907e2177eb8
comparison
equal deleted inserted replaced
42:24af9a14b203 44:f5b5c648cd5d
1 /*
2 * udpServer.cpp
3 *
4 * Created on: 19 May 2015
5 * Author: giulio moro
6 */
7 #include "../include/UdpServer.h"
8
9 UdpServer::UdpServer(int aPort){
10 init(aPort);
11 };
12 UdpServer::UdpServer(){
13 init(0);
14 }
15 UdpServer::~UdpServer(){
16
17 };
18 bool UdpServer::init(int aPort){
19 enabled=true;
20 stTimeOut.tv_sec = 0; //set timeout to 0
21 stTimeOut.tv_usec = 0;
22 inSocket=socket(AF_INET, SOCK_DGRAM, 0);
23 if (inSocket < 0){
24 enabled=false;
25 }
26 length = sizeof(server);
27 server.sin_family=AF_INET;
28 server.sin_addr.s_addr=INADDR_ANY;
29 enabled=bindToPort(aPort);
30 wasteBufferSize=2048;
31 wasteBuffer=malloc(wasteBufferSize);
32 return enabled;
33 }
34
35 bool UdpServer::bindToPort(int aPort){
36 port=aPort;
37 server.sin_port=htons(port);
38 if (bind(inSocket,(struct sockaddr *)&server,length)<0){
39 enabled=false;
40 return false;
41 }
42 return true;
43 };
44 int UdpServer::read(//Returns the number of bytes read, or -1 if there was an error.
45 void *destBuffer,
46 int maxBytesToRead){
47 if(enabled==false)
48 return -1;
49 FD_ZERO(&stReadFDS);
50 FD_SET(inSocket, &stReadFDS);
51 int descriptorReady= select(inSocket+1, &stReadFDS, NULL, NULL, &stTimeOut);
52 if(descriptorReady<0){ //an error occurred
53 return -1;
54 }
55 int numberOfBytes=0;
56 if (FD_ISSET(inSocket, &stReadFDS)) {
57 numberOfBytes=recvfrom(inSocket,destBuffer,maxBytesToRead,0,(struct sockaddr *)&from,&fromLength);
58 if(numberOfBytes<0)
59 return -1;
60 }
61 return numberOfBytes;
62 };
63 int UdpServer::emptySocket(){
64 return emptySocket(0);
65 }
66 int UdpServer::emptySocket(int maxBytes){//discards up to maxBytes from the socket. Returns the number of bytes discarded.
67 if(wasteBuffer==NULL)
68 return -1;
69 int numberOfBytes=0;
70 while(int n=read(wasteBuffer, wasteBufferSize)){// calls the read function until it does not return any more bytes (i.e.: socket is empty)
71 if(n>0)
72 numberOfBytes+=n;
73 if(n<0)
74 return -1;
75 if(maxBytes>0 && numberOfBytes>=maxBytes)
76 break;
77 };
78 return numberOfBytes;
79 }
80 void* UdpServer::getWaste(){ //returns the last datagram retrieved by emptySocket()
81 return wasteBuffer;
82 }
83