Solved

TCP C++

Posted on 2001-08-27
6
567 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 25 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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

758 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now