Link to home
Start Free TrialLog in
Avatar of Toad224
Toad224Flag for United States of America

asked on

TCP C++

I need a simple program that connects to a host using TCP, and sends a specific string about every 5
seconds.  If I get disconnected from the host, I want it to automatically reconnect.  I also need it
to bind to a certain IP.  It needs to compile for unix / linux I've tried some things, but I could never get it to work...  Here's what I got in perl so far...  It doesn't work, I'm probably not even close, but I want it in C++ instead.


#!/usr/bin/perl

use IO::Socket;

my $shost = "localhost";

for($count = 1; $count <= 4; $count)
{
    $sock = new IO::Socket::INET (
                                     #LocalHost => "66.40.69.20",
                                     PeerAddr => "$shost",
                         PeerPort => '80',
                                     Proto => 'tcp',
                                    );
    #die "Could not create socket: $!\n" unless $sock;
    $sock->autoflush(1);
   
    print $sock "GET /update.cgi?k HTTP/1.0\r\nHost: $shost\r\nConnection: keep-alive\r\n\r\n";

    while($bob)
    {
         $bob = <$sock>;
         print $bob;
         #sleep(3);
         #$status = print $sock "";
         $status = print $sock " ";
         #printf("?");

         $exitloop = 1 unless $sock;
    }
}
Avatar of pamboo
pamboo

Here is a class what u need...Hope it is easier to use in ur application...

/////////////////////////////////////
mySocket.h
/////////////////////////////////////
#include<winsock.h>
#include<stdlib.h>
#include<string.h>

class myTCPsocket
{  
  private:
  SOCKET soc;
  char *Data;

  public:
  myTCPsocket(SOCKET s)
  {
     soc=s;          
  }

  myTCPsocket()
  {
  }

  static void InitSocket(int);
  int Create();
  int Bind(int);
  int Connect(char*,int);
  SOCKET Accept();
  int Listen(int);
  char* Receiveln(int);
  int Send(CString);
  void Close(void);
};
/***************************************************************/
static void myUDPSocket::InitSocket(int version)
{
   WSADATA wsadata;
   WSAStartup(version,&wsadata); //0x0101
}
/***************************************************************/
int myTCPsocket::Create()
{
    soc=socket(AF_INET,SOCK_STREAM,0);
    if (soc==INVALID_SOCKET) return INVALID_SOCKET;
    return true;
}
/***************************************************************/
int myTCPsocket::Bind(int Port)
{
    struct sockaddr_in serv_addr;
   
    serv_addr.sin_family        = AF_INET;      
    serv_addr.sin_addr.s_addr   = htonl(INADDR_ANY);
    serv_addr.sin_port          = htons(Port);                
     
    if(bind(soc,(struct sockaddr *)&serv_addr,sizeof (serv_addr))==SOCKET_ERROR)return SOCKET_ERROR;
   
    return true;
}
/***************************************************************/
int myTCPsocket::Connect(char* IP,int Port)
{
    struct sockaddr_in serv_addr;
   
    serv_addr.sin_family        = AF_INET;      
    serv_addr.sin_addr.s_addr   = inet_addr(IP);
    serv_addr.sin_port          = htons(Port);                
     
    if(connect(soc,(struct sockaddr *)&serv_addr,sizeof(serv_addr))==SOCKET_ERROR) return SOCKET_ERROR;

    return true;
}
/***************************************************************/
int myTCPsocket::Listen(int ql)
{
  return(listen(soc,ql));
}
/***************************************************************/
SOCKET myTCPsocket::Accept()
{
    SOCKET acc_soc;

    struct sockaddr_in client_addr;
    int client_addr_len =sizeof(client_addr);
    acc_soc=accept(soc,(struct sockaddr *)   &client_addr,&client_addr_len);
   
    return acc_soc;
}
/***************************************************************/
char* myTCPsocket::Receiveln(int nBytes)
{  
    char *buf;
    buf =(char*) malloc(nBytes);    
    recv(soc,buf,nButes,0);  
    Data=buf;
    return temp;
}
/***************************************************************/
int myTCPsocket::Send(char* data)
{  
    int x;
    x=send(soc,data,strlen(data),0);
    return x;      
}

/***************************************************************/
void myTCPsocket::Close()
{  
 closesocket(soc);
}
/***************************************************************/

Thank u ,
bye.
S.Nagarajan
ASKER CERTIFIED SOLUTION
Avatar of AlexVirochovsky
AlexVirochovsky

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Toad224

ASKER

Like I said... It needs to compile for unix / linux ...    One of my problems is that when I'm going to receive, the program is blocking, and I won't be able to send data every 5 sec.  I'm not having that much trouble witht he actual sending of the data to the host...  more with needing to send every 5 sec., and reconnect if disconnected.
For unix/linux ...The adove code uses BSD standards only ...So it can be compiled in UNIX environment too....Just change the Header files which contains these APIS for UNIX environmet...In windows all are enclosed in one header itself i.e.<winsock.h>...where as unix u have to include <sys/types.h> , <sys/net.h> and so on....

To achieve non-blocking data receive ...One easy solution is U can fork the receiving module of ur program...It will become a seperate process then...The data/message transfer between different processes can be achieved using UNIX various IPCs techniques...(For eg.. PIPES,Shared memory)
If you want covert Perl to C, may be will be useful
some advices:
http://www.perl.com/pub/a/2001/06/27/ctoperl.html
You can also use the pthread, or any other thread library of your desire to run the send timer and the listener in parallel.  The advantage to using threads versus forking is that your threads will run in the same process space and therefore do not require any touchy IPC adapters to communicate.  However, you do need to make sure that any shared methods/objects have the appropriate mutex locks such that they are thread safe....

Ok, that said..  The easiest way to set up the timer is to use a sigint (signal interrupt) handler.  These are actually very easy to use.  First, do a "man signal" then "man 7 signal".  The signal you would want to use is SIGALRM.  Use the alarm() function to set the interval of the alarm callback.  That's it...  I'll put a basic example below.

You need the following includes.
#include<unistd.h>
#include<signal.h>
...
   /* send a sigalarm every 5 seconds */
   alarm(5);

   /* This will execute a c style function called sendData every 5 seconds. */
   signal(SIGALRM, sendData);

   /* I think this is right, hehe.  This will execute the sendData method in the data object.  This is because C++ methods are referenced as an offset from the beginning of the object, so you have to add the base memory reference back in.  You could also call a C function and have it call your method for you, up to you  */
   Data data = new Data("Send this string");
   signal(SIGALRM, data + data->sendData);

.....

You would define your function, or method like this:

/* for C function */
void sendData(int fileDesc) {
   /* Send your stuff here */
}

/* for C++ method */

class Data {
   Data(String blah){...}

   void sendData(int fileDesc) { /* send your stuff here */ }

}