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 _VRUDPSOURCE_H_
00038 #define _VRUDPSOURCE_H_
00039
00040 #include <VrSource.h>
00041
00042 #include <string.h>
00043 #include <sys/types.h>
00044 #include <netinet/in.h>
00045 #include <sys/socket.h>
00046 #include <sys/wait.h>
00047 #include <arpa/inet.h>
00048 #include <netinet/in.h>
00049
00050 #define MAX_UDP_SIZE 3000
00051
00052 template<class oType>
00053 class VrUDPSource : public VrSource<oType> {
00054 protected:
00055 int sockfd;
00056 struct sockaddr_in my_addr;
00057 struct sockaddr_in their_addr;
00058 unsigned char tempbuf[MAX_UDP_SIZE];
00059 int tempbuf_index, tempbuf_size;
00060 public:
00061 virtual const char *name() { return "VrUDPSource"; }
00062
00063 virtual int work2(VrSampleRange output, void *o[]);
00064
00065 VrUDPSource (double sampling_freq, int port);
00066 virtual ~VrUDPSource() {}
00067 };
00068
00069 template<class oType> int
00070 VrUDPSource<oType>::work2(VrSampleRange output, void *ao[])
00071 {
00072 oType **o= (oType **)ao;
00073 unsigned int addr_len = sizeof(struct sockaddr);
00074 int size = output.size * sizeof(oType);
00075 unsigned char *cp = (unsigned char *)o[0];
00076 int temp;
00077
00078
00079 printf ("[%s] work %ld\n", __FILE__, output.size);
00080 while (size > 0) {
00081 if (tempbuf_size > 0) {
00082 *cp++ = tempbuf[tempbuf_index++];
00083 tempbuf_size--;
00084 size--;
00085 continue;
00086 }
00087 if (size < MAX_UDP_SIZE) {
00088 tempbuf_index = 0;
00089 tempbuf_size = recvfrom(sockfd, tempbuf, sizeof(tempbuf), 0,
00090 (struct sockaddr *)&their_addr, &addr_len);
00091 continue;
00092 }
00093 temp = recvfrom(sockfd, cp, size, 0,
00094 (struct sockaddr *)&their_addr, &addr_len);
00095 if (temp > 0){
00096
00097 printf ("received %d bytes from %s\n", temp, inet_ntoa(their_addr.sin_addr) );
00098 size -= temp;
00099 cp += temp;
00100 }
00101 else {
00102 printf ("[%s:%d] error in recvfrom %d\n", __FILE__, __LINE__, errno);
00103 break;
00104 }
00105 }
00106 return (int)output.size;
00107 }
00108
00109 template<class oType>
00110 VrUDPSource<oType>::VrUDPSource(double sampling_freq, int port)
00111 {
00112 setSamplingFrequency (sampling_freq);
00113 tempbuf_index = 0;
00114 tempbuf_size = 0;
00115 if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
00116 perror("socket");
00117 exit(1);
00118 }
00119 my_addr.sin_family = AF_INET;
00120 my_addr.sin_port = htons(port);
00121 my_addr.sin_addr.s_addr = INADDR_ANY;
00122 bzero(&(my_addr.sin_zero), 8);
00123
00124 if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
00125 perror("bind");
00126 exit(1);
00127 }
00128 }
00129 #endif