00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037 #ifndef _VRUDPSINK_H_
00038 #define _VRUDPSINK_H_
00039
00040 #include <VrSink.h>
00041 #include <fstream>
00042 #include <sys/socket.h>
00043 #include <string.h>
00044 #include <sys/types.h>
00045 #include <netinet/in.h>
00046 #include <sys/wait.h>
00047 #include <netdb.h>
00048 #include <arpa/inet.h>
00049 #include <netinet/in.h>
00050
00051 #include <sys/time.h>
00052 #include <unistd.h>
00053
00054 #define MAX_UDP 1990
00055 template<class iType>
00056 class VrUDPSink : public VrSink<iType> {
00057 private:
00058 int sockfd;
00059 int outputsize;
00060 struct sockaddr_in their_addr;
00061 struct hostent *he;
00062 long long next_time;
00063
00064 public:
00065 virtual const char *name() { return "VrUDPSink"; }
00066 virtual int work3(VrSampleRange output,
00067 VrSampleRange inputs[], void *i[]);
00068
00069 virtual void initialize() {
00070 if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
00071 perror("socket");
00072 exit(1);
00073 }
00074 }
00075
00076 VrUDPSink(char* hostname, int port) {
00077 next_time = 0;
00078 if ((he=gethostbyname(hostname)) == NULL) {
00079 herror("gethostbyname");
00080 exit(1);
00081 }
00082 their_addr.sin_family = AF_INET;
00083 their_addr.sin_port = htons(port);
00084 their_addr.sin_addr = *((struct in_addr *)he->h_addr);
00085 bzero(&(their_addr.sin_zero), 8);
00086 }
00087 virtual ~VrUDPSink() { }
00088 };
00089
00090 template<class iType> int
00091 VrUDPSink<iType>::work3(VrSampleRange output,
00092 VrSampleRange inputs[], void *ai[])
00093 {
00094 struct timeval now;
00095 long long this_time;
00096 int current, temp;
00097 int left=output.size*sizeof(iType);
00098 unsigned char *cp = (unsigned char *)ai[0];
00099
00100 gettimeofday(&now,NULL);
00101 this_time = now.tv_sec * (long long) 1000000 + now.tv_usec;
00102 if (this_time < next_time)
00103 usleep ((int) (next_time - this_time));
00104
00105 double usecs_per_sample = 1e6 / getSamplingFrequency ();
00106
00107 next_time = this_time + (long long) (output.size * usecs_per_sample);
00108 while (left > 0) {
00109 current = left;
00110 if (current > MAX_UDP)
00111 current = MAX_UDP;
00112
00113 temp =sendto(sockfd, cp, current, 0,
00114 (struct sockaddr *)&their_addr, sizeof(struct sockaddr));
00115
00116
00117
00118 if (temp>0){
00119 cp += temp;
00120 left -= temp;
00121 }
00122 else {
00123
00124 break;
00125 }
00126 }
00127 return output.size;
00128 }
00129
00130 #endif