diff 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
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/core/UdpServer.cpp	Wed May 20 18:07:16 2015 +0100
@@ -0,0 +1,83 @@
+/*
+ * 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;
+	server.sin_port=htons(port);
+	if (bind(inSocket,(struct sockaddr *)&server,length)<0){
+		enabled=false;
+		return false;
+	}
+	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;
+}
+