Solved

TCP C++

Posted on 2001-08-27
6
575 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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

Want Experts Exchange at your fingertips?

With Experts Exchange’s latest app release, you can now experience our most recent features, updates, and the same community interface while on-the-go. Download our latest app release at the Android or Apple stores today!

Question has a verified solution.

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

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
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 viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

627 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