Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

TCP C++

Posted on 2001-08-27
6
Medium Priority
?
579 Views
Last Modified: 2007-12-19
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;
    }
}
0
Comment
Question by:Toad224
6 Comments
 
LVL 3

Expert Comment

by:pamboo
ID: 6430686
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
0
 
LVL 14

Accepted Solution

by:
AlexVirochovsky earned 75 total points
ID: 6430754
0
 
LVL 1

Author Comment

by:Toad224
ID: 6431104
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.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 3

Expert Comment

by:pamboo
ID: 6431303
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)
0
 
LVL 14

Expert Comment

by:AlexVirochovsky
ID: 6431332
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
0
 
LVL 5

Expert Comment

by:BlackDiamond
ID: 6434588
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 */ }

}
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

877 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question