How to pass socket to a loop
May 22, 2013 at 6:25am UTC
I want to have the following process:
1. create socket to server
2. loop
send data to socket
end loop
I can't figure out how to pass the int socket into the loop module
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
#include "eHealth.h"
#include "ecg.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
void setup(){
int status;
int socketfd;
struct addrinfo host_info;
struct addrinfo *host_info_list;
memset(&host_info, 0, sizeof (host_info));
host_info.ai_family=AF_INET;
host_info.ai_socktype=SOCK_STREAM;
status=getaddrinfo("192.168.0.112" , "6001" , &host_info, &host_info_list);
if (status==-1) std::cout << "getaddrinfo error" ;
socketfd=socket(host_info_list->ai_family, host_info_list->ai_socktype,host_info_list->ai_protocol);
if (socketfd==-1) std::cout << "socket error" ;
status=connect(socketfd, host_info_list->ai_addr, host_info_list->ai_addrlen);
if (status==-1) std::cout << "connect error" ;
}
// The loop routine runs over and over again forever:
void loop() {
extern int socketfd;
float ECG = eHealth.getECG();
std::ostringstream ostr;
ostr<<ECG;
std::string ECGmsg=ostr.str();
int len;
std::string msg=ECGmsg+" \n" ;
int bytes_sent;
len=strlen(msg.c_str());
bytes_sent=send(socketfd,msg.c_str(),len,0);
delay(250);
}
int main (){
setup();
while (1){
loop();
}
return (0);
}
May 22, 2013 at 7:00am UTC
let
setup()
return the
socketfd
and pass that as a parameter to
loop()
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
int setup(){
int status;
int socketfd;
...
return socketfd;
}
// The loop routine runs over and over again forever:
void loop(int socketfd ) {
extern int socketfd;
...
}
int main (){
int socketfd = setup();
while (1){
loop(socketfd );
}
return (0);
}
Topic archived. No new replies allowed.