GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 23-Feb-2006, 11:13
TreyAU21's Avatar
TreyAU21 TreyAU21 is offline
Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 116
TreyAU21 has a spectacular aura aboutTreyAU21 has a spectacular aura about

G++ question...


Hi All,

This is my first post on these forums, and I'm hoping some of you can help me. First of all, I'm a Java guy, but I've dabbled in C and C++ in the past.

I've purchased a book called "Multiplayer Game Programming" in which the author uses C++ as his laguage of choice. The author of this book assumes that the reader is using Microsoft's Visual Studio, and steps the reader through to associate libraries and what not inside that software package so that his code with compile properly. I don't have Visual Studio, and I'm trying to compile and link his programs using g++ at the command line. His first program is a Simple ClientConnectionTest program that uses winsock2.h. He (along with everything I could find on the internet) said that you must associate the library ws2_32.lib to this build. Is there any way to associate this library on the command prompt for g++ without creating a makefile.

Thanks,
Trey
  #2  
Old 23-Feb-2006, 11:36
Chris.Dev's Avatar
Chris.Dev Chris.Dev is offline
Junior Member
 
Join Date: Jan 2005
Posts: 48
Chris.Dev will become famous soon enough

Re: G++ question...


What software package are you using?

For mingw:
-lws2_32

For Cygwin:
do the same but also add -mno-cygwin

That should do the trick.
  #3  
Old 23-Feb-2006, 12:20
TreyAU21's Avatar
TreyAU21 TreyAU21 is offline
Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 116
TreyAU21 has a spectacular aura aboutTreyAU21 has a spectacular aura about

Re: G++ question...


Thanks for the help. That did get rid of some of the compiler errors I was getting that I thought were associated with not linking that library. however some more have cropped up. I am using cygwin by the way, so the command I used was "g++ -lws2_32 -mno-cygwin ConnectionTest.cpp". I struggled with this for a couple of hours last night, so I'm quite frustrated with it. So, maybe you can help me along to get this compiled. I truly appreciate all of the help.

I'm just not used to the compiler errors that the g++ compiler is giving me. That comes with use as we all know. I just don't know what it's trying to tell me know. Here are the NEW compiler errors (it's almost like it doesn't see the SocketObject header file).
Code:
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccVweeM8.o:ConnectionTest.cpp: (.text+0x2dc): undefined reference to `_WSACleanup@0' /cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccVweeM8.o:ConnectionTest.cpp: (.text+0x348 ): undefined reference to `SocketObject::SocketObject()' /cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccVweeM8.o:ConnectionTest.cpp: (.text+0x360): undefined reference to `SocketObject::SocketObject()' /cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccVweeM8.o:ConnectionTest.cpp: (.text+0x3b4): undefined reference to `SocketObject::Bind(int)' /cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccVweeM8.o:ConnectionTest.cpp: (.text+0x3ee): undefined reference to `SocketObject::Listen()'
... it goes on to list every function in the SocketObject class.

Here is some of the code (the SocketObject.h):
CPP / C++ / C Code:
#ifndef SOCKET_OBJECT

#define SOCKET_OBJECT

// Windows Sockets Include, Also need ws2_32.lib included in project
#include <winsock2.h>
#include <stdio.h>

struct stPacketHeader
{
	int		iType;
	int		iLength;
	int		iID;
	int		iCheckSum;
	int		iSender;
};

struct SocketTransmissionStruct 
{
	SOCKET		skSocket;
	char		szBuffer[64000];
	int			iWritePos;
	int			iReadPos;
	int			iTerminate;
};

// Class Object
class SocketObject  
{
	private:

	public:
		SOCKET						skSocket;
		int							iStatus;
		SocketTransmissionStruct	stReceive;	
		SocketTransmissionStruct	stSend;	
		DWORD						dwReceiveHandle;
		DWORD						dwSendHandle;

		// Constructor
		SocketObject();
		// Desctrucot
		~SocketObject();

		// Accept a client's request to connect
		bool Accept(SocketObject& skAcceptSocket);
		// Listen for clients to connect
		int Listen( void );
		// Open a server listening port
		int Bind(int iPort);
		// Close connection
		void Disconnect();
		// Connect to a server
		bool Connect(char* szServerAddress, int iPort);

		int Recv(char *szBuffer, int iBufLen, int iFlags);
		int Send(char *szBuffer, int iBufLen, int iFlags);

		// Misc Functions
		int iCalculateChecksum(stPacketHeader stHead);

		// Asynchronous Functions
		static void thrReceiveThread(SocketTransmissionStruct *rs);
		static void thrSendThread(SocketTransmissionStruct &rs);
		int vGetPacket(char *szbuffer);
};

That was all of the code... but all I was wanting you to see was the SocketObject class. This next code is what the error messages are actually referring to. It's got to be something to with the includes, but I put the whole file there in case you are curious. I'm nt sure why all of the Socket Objects are getting the "undefined reference" error? Help? Here is the ConnectionTest.c file:
CPP / C++ / C Code:
#include <iostream>
#include "..\\SocketObject\\SocketObject.h"

   using namespace std;

   void vServerConnection( int iListenPort );
   void vClientConnection( char *szServerIP, int iServerListenPort );

//	
// ----> Main Program Function (REQUIRED)
//
    int main( int argc, char *argv[] )
   {
      if( argc < 3 ) {
         cout << "----------------------------------------------------" << endl;
         cout << "               ConnectionTest Help                  " << endl;
         cout << "----------------------------------------------------" << endl;
         cout << "Usage: ConnectionTest [client/server] [ip,port/port]" << endl;
         cout << "" << endl;
         cout << "Example: ConnectionTest client 198.168.0.1 6000" << endl;
         cout << "" << endl;
         cout << "Example: ConnectionTest server 6000" << endl;
         cout << "" << endl;
         return( 0 );
      }
   
   //
   // If user selected server, listen on the given port 
   //
      if( !stricmp( argv[1], "server" ) )
      {
         vServerConnection( atoi( argv[2] ) );
      }
      //
      // User selected client, connect to given port and IP address
      //
      else {
         vClientConnection( argv[2], atoi( argv[3] ) );	
      }
   
      WSACleanup();
   
      return( 1 );
   }

// Function for server
    void vServerConnection( int iListenPort  )
   {
      SocketObject	ServerSocketObject;		
      SocketObject	ClientSocketObject;		
   
      cout << "<Server> Attempting to listen on Port " << iListenPort << endl;
   
   // Attempt to start the server on port 6000
      if ( ServerSocketObject.Bind( iListenPort ) )
      {
         cout << "<Server> Listening" << endl;
      
      // Listen for connection on the Listen port, 
         ServerSocketObject.Listen();
      
      // Accept the connection
         ServerSocketObject.Accept( ClientSocketObject );
      
         cout << "<Server> Client Connected to Port " << iListenPort << endl;
      
      // Disconnect the client
         ClientSocketObject.Disconnect();
      
         cout << "<Server> Client Disconnected" << endl;
      }
      else {
         cout << "<Server> Failed to Listen" << endl;
      }
   }

// Function for client
    void vClientConnection( char *szServerIP, int iServerListenPort )
   {
      SocketObject	ClientSocketObject;
   
      cout << "<Client> Connecting to " << szServerIP << ", Port " << iServerListenPort << endl;
   
   // Connect to the IP and Port 
      if( ClientSocketObject.Connect( szServerIP, iServerListenPort ) )
      {
         cout << "<Client> Connected" << endl;
      
      // Disconnect from the server
         ClientSocketObject.Disconnect();
      
         cout << "<Client> Disconnected From Server" << endl;
      }
      else {
         cout << "<Client> Failed to Connect" << endl;
      }
   }
Last edited by cable_guy_67 : 23-Feb-2006 at 12:29. Reason: Please enclose c++ code in [c++] ... [/c++] tags
  #4  
Old 23-Feb-2006, 12:40
cable_guy_67's Avatar
cable_guy_67 cable_guy_67 is offline
Senior Member
 
Join Date: Oct 2004
Location: Nescopeck, PA
Posts: 1,109
cable_guy_67 is a jewel in the roughcable_guy_67 is a jewel in the roughcable_guy_67 is a jewel in the roughcable_guy_67 is a jewel in the rough

Re: G++ question...


Do you by any chance have a SocketObject.cpp file somewhere that could be compiled with the rest...

Mark
__________________
"Opportunity is missed by most people because it comes dressed in overalls and looks like work."
--Thomas Alva Edison
"Those who would give up essential liberty to purchase a little temporary safety, deserve neither liberty nor safety."
--Benjamin Franklin
"A happy person is not a person in a certain set of circumstances, but rather a person with a certain set of attitudes."
--Hugh Downs
  #5  
Old 23-Feb-2006, 13:00
TreyAU21's Avatar
TreyAU21 TreyAU21 is offline
Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 116
TreyAU21 has a spectacular aura aboutTreyAU21 has a spectacular aura about

Re: G++ question...


I thought it would probably be something simple to do with my lack of knowledge of the linker. I'm so spoiled by Java. I'm still getting several undefined reference errors.

g++ -mno-cygwin -lws2_32 ConnectionTest.cpp SocketObject.cpp

There's probably something I'm not doing right. Are there other libraries I need? IS that the proper syntax or order for the command? Here is a sampling of some of the errors that I'm getting now. Some went away... but more new ones came. Gotta love when that happens:

SocketObject.cpp: In member function `bool SocketObject::Connect(char*, int)':
SocketObject.cpp:168: warning: converting to non-pointer type `char' from NULL
SocketObject.cpp:181: warning: passing NULL used for non-pointer converting 2 of `void* CreateThread(_SECURITY_ATTRIBUTES*, DWORD, DWORD (*)(void*), void*, DWOR
D, DWORD*)'
SocketObject.cpp:181: warning: passing NULL used for non-pointer converting 5 of `void* CreateThread(_SECURITY_ATTRIBUTES*, DWORD, DWORD (*)(void*), void*, DWORD, DWORD*)'
SocketObject.cpp: In member function `bool SocketObject::Accept(SocketObject&)':

SocketObject.cpp:244: warning: converting to non-pointer type `char' from NULL
SocketObject.cpp:257: warning: passing NULL used for non-pointer converting 2 of `void* CreateThread(_SECURITY_ATTRIBUTES*, DWORD, DWORD (*)(void*), void*, DWORD, DWORD*)'
SocketObject.cpp:257: warning: passing NULL used for non-pointer converting 5 of `void* CreateThread(_SECURITY_ATTRIBUTES*, DWORD, DWORD (*)(void*), void*, DWORD, DWORD*)'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccb1ZaF7.o:ConnectionTest.cpp: (.text+0x2dc): undefined reference to `_WSACleanup@0'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x34): undefined reference to `_WSAStartup@8'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x78 ): undefined reference to `_WSAStartup@8'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x27b): undefined reference to `_recv@16'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x395): undefined reference to `_send@16'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x3d1): undefined reference to `_inet_addr@4'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x3e8 ): undefined reference to `_gethostbyname@4'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x40f): undefined reference to `_WSASetLastError@4'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x42c): undefined reference to `_htons@4'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x452): undefined reference to `_socket@12'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x487): undefined reference to `_connect@12'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x547): undefined reference to `_closesocket@4'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x57c): undefined reference to `_socket@12'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x5c2): undefined reference to `_htonl@4'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x5d6): undefined reference to `_htons@4'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x5f9): undefined reference to `_bind@12'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x63f): undefined reference to `_listen@8'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x670): undefined reference to `_accept@12'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x77c): undefined reference to `_recv@16'
/cygdrive/c/DOCUME~1/TREY~1.WHI/LOCALS~1/Temp/ccqprnsj.o:SocketObject.cpp: (.text+0x7aa): undefined reference to `_send@16'
  #6  
Old 23-Feb-2006, 13:06
Chris.Dev's Avatar
Chris.Dev Chris.Dev is offline
Junior Member
 
Join Date: Jan 2005
Posts: 48
Chris.Dev will become famous soon enough

Re: G++ question...


Your source code is incomplete. You should look through the book, (maybe in the back). It should have the source code for the class in there to. If you have the code to that class please post it so we can have a look

You could try manually linking "libws2_32.a"

make sure that that file is in your cygwin/lib/w32api folder as well.
  #7  
Old 23-Feb-2006, 13:42
TreyAU21's Avatar
TreyAU21 TreyAU21 is offline
Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 116
TreyAU21 has a spectacular aura aboutTreyAU21 has a spectacular aura about

Re: G++ question...


Ok... here is all the code. This is pretty much a straight copy and paste from the CD that came with the book. I would like to add that this book was written 4 or 5 years ago, so some of the conventions are probably a little old. I appreciate everyone's help on this matter:

Driver file (TestConnection.c):

CPP / C++ / C Code:
// Standard Includes

#include <iostream>
#include "SocketObject.h"

   using namespace std;

   void vServerConnection( int iListenPort );
   void vClientConnection( char *szServerIP, int iServerListenPort );

//	
// ----> Main Program Function (REQUIRED)
//
    int main( int argc, char *argv[] )
   {
      if( argc < 3 ) {
         cout << "----------------------------------------------------" << endl;
         cout << "               ConnectionTest Help                  " << endl;
         cout << "----------------------------------------------------" << endl;
         cout << "Usage: ConnectionTest [client/server] [ip,port/port]" << endl;
         cout << "" << endl;
         cout << "Example: ConnectionTest client 198.168.0.1 6000" << endl;
         cout << "" << endl;
         cout << "Example: ConnectionTest server 6000" << endl;
         cout << "" << endl;
         return( 0 );
      }
   
   //
   // If user selected server, listen on the given port 
   //
      if( !stricmp( argv[1], "server" ) )
      {
         vServerConnection( atoi( argv[2] ) );
      }
      //
      // User selected client, connect to given port and IP address
      //
      else {
         vClientConnection( argv[2], atoi( argv[3] ) );	
      }
   
      WSACleanup();
   
      return( 1 );
   }

// Function for server
    void vServerConnection( int iListenPort  )
   {
      SocketObject	ServerSocketObject;		
      SocketObject	ClientSocketObject;		
   
      cout << "<Server> Attempting to listen on Port " << iListenPort << endl;
   
   // Attempt to start the server on port 6000
      if ( ServerSocketObject.Bind( iListenPort ) )
      {
         cout << "<Server> Listening" << endl;
      
      // Listen for connection on the Listen port, 
         ServerSocketObject.Listen();
      
      // Accept the connection
         ServerSocketObject.Accept( ClientSocketObject );
      
         cout << "<Server> Client Connected to Port " << iListenPort << endl;
      
      // Disconnect the client
         ClientSocketObject.Disconnect();
      
         cout << "<Server> Client Disconnected" << endl;
      }
      else {
         cout << "<Server> Failed to Listen" << endl;
      }
   }

// Function for client
    void vClientConnection( char *szServerIP, int iServerListenPort )
   {
      SocketObject	ClientSocketObject;
   
      cout << "<Client> Connecting to " << szServerIP << ", Port " << iServerListenPort << endl;
   
   // Connect to the IP and Port 
      if( ClientSocketObject.Connect( szServerIP, iServerListenPort ) )
      {
         cout << "<Client> Connected" << endl;
      
      // Disconnect from the server
         ClientSocketObject.Disconnect();
      
         cout << "<Client> Disconnected From Server" << endl;
      }
      else {
         cout << "<Client> Failed to Connect" << endl;
      }
   }



Socket Object Header File (SocketObject.h)

CPP / C++ / C Code:
#ifndef SOCKET_OBJECT

#define SOCKET_OBJECT

// Windows Sockets Include, Also need ws2_32.lib included in project
#include <winsock2.h>
#include <stdio.h>

struct stPacketHeader
{
	int		iType;
	int		iLength;
	int		iID;
	int		iCheckSum;
	int		iSender;
};

struct SocketTransmissionStruct 
{
	SOCKET		skSocket;
	char		szBuffer[64000];
	int			iWritePos;
	int			iReadPos;
	int			iTerminate;
};

// Class Object
class SocketObject  
{
	private:

	public:
		SOCKET						skSocket;
		int							iStatus;
		SocketTransmissionStruct	stReceive;	
		SocketTransmissionStruct	stSend;	
		DWORD						dwReceiveHandle;
		DWORD						dwSendHandle;

		// Constructor
		SocketObject();
		// Desctrucot
		~SocketObject();

		// Accept a client's request to connect
		bool Accept(SocketObject& skAcceptSocket);
		// Listen for clients to connect
		int Listen( void );
		// Open a server listening port
		int Bind(int iPort);
		// Close connection
		void Disconnect();
		// Connect to a server
		bool Connect(char* szServerAddress, int iPort);

		int Recv(char *szBuffer, int iBufLen, int iFlags);
		int Send(char *szBuffer, int iBufLen, int iFlags);

		// Misc Functions
		int iCalculateChecksum(stPacketHeader stHead);

		// Asynchronous Functions
		static void thrReceiveThread(SocketTransmissionStruct *rs);
		static void thrSendThread(SocketTransmissionStruct &rs);
		int vGetPacket(char *szbuffer);
};

#endif

SocketObject Source File (SocketObject.cpp)

CPP / C++ / C Code:
#include "SocketObject.h"

// Constructor
    SocketObject::SocketObject()
   {
      WSADATA wsaData;
      WORD	wVersionRequested;
   
      wVersionRequested = MAKEWORD( 2, 0 );
   
      skSocket = INVALID_SOCKET;
      iStatus = WSAStartup(wVersionRequested,&wsaData);
   }

// Destructor
    SocketObject::~SocketObject()
   {
      CloseHandle(&dwReceiveHandle);
      Disconnect();
   }

    int SocketObject::vGetPacket(char *szbuffer)
   {
      int				iBytesReceived = 0;
      int				iBytesWaiting = 0;
      stPacketHeader	stHeader;
   
   // Check if write pos moved
      if( stReceive.iWritePos != stReceive.iReadPos ) {
      //
      // Pull packet header from buffer
      //
         iBytesWaiting = (stReceive.iWritePos - stReceive.iReadPos);
      // Make sure a full size header is present
         if( iBytesWaiting < sizeof(stHeader) ) {
            return(0);
         }
      // Copy the header in
         memcpy(&stHeader,&stReceive.szBuffer[stReceive.iReadPos],sizeof(stHeader));
      // Check the checksum
         if( ((stHeader.iType+stHeader.iLength+stHeader.iID)) != stHeader.iCheckSum ) {
         // Skip the first bad byte in an attempt to find a good packet
            stReceive.iReadPos++;
            if( stReceive.iReadPos >= 64000 ) {
               stReceive.iReadPos = 0;
            }
         // Try again for a good packet
            vGetPacket(szbuffer);
         }
         else {
         }
      
      //
      // Pull the body of the packet according to the size 
      //
      
      // Make sure enough data is waiting, if not leave and try again later
         if( (iBytesWaiting-sizeof(stHeader)) < (unsigned)stHeader.iLength ) {
            return(0);
         }
      // Copy into the return buffer
         memcpy(szbuffer,&stHeader,sizeof(stHeader));
         memcpy(&szbuffer[sizeof(stHeader)],&stReceive.szBuffer[stReceive.iReadPos+sizeof(stHeader)],stHeader.iLength);
      
      // Update Read Position & Return Values
         stReceive.iReadPos += (stHeader.iLength+sizeof(stHeader));
         iBytesReceived = (stHeader.iLength+sizeof(stHeader));
      
      // Check if reading too far
         if( stReceive.iReadPos >= 64000 ) {
            stReceive.iReadPos = 0;
         }
      }
   
      return(iBytesReceived);
   }

    void SocketObject::thrReceiveThread(SocketTransmissionStruct *rs)
   {
      int				iBytesReceived;
      char			*szTempBuffer;
      int				iBytesPart1;
      int				iBytesPart2;
   
      szTempBuffer = new char[32768];
   
   // Receive data until given notice to terminate
      while( rs->iTerminate != 1 ) {
      // Read from the pipe
         iBytesReceived = recv( rs->skSocket, szTempBuffer, 32768, 0 );
         if( iBytesReceived > 0 ) {
         // Make sure the packet does not overrun the write buffer
            if( (rs->iWritePos+iBytesReceived) >= 64000 ) {
               iBytesPart1 = ((rs->iWritePos+iBytesReceived)-64000);
               iBytesPart2 = (64000 - rs->iWritePos);
               memcpy( &rs->szBuffer[rs->iWritePos], szTempBuffer, iBytesPart1 );
               memcpy( &rs->szBuffer[0], &szTempBuffer[iBytesPart1], iBytesPart2 );
               rs->iWritePos = iBytesPart2;
            }
            else {
            // Write to the permanent buffer
               memcpy( &rs->szBuffer[rs->iWritePos], szTempBuffer, iBytesReceived );
               rs->iWritePos += iBytesReceived;
            }
         }
      }
   
      delete [] szTempBuffer;
   }

    void SocketObject::thrSendThread(SocketTransmissionStruct &rs)
   {
      int iBytesSent;
   
      iBytesSent = send( rs.skSocket, rs.szBuffer, 128, 0 );
   }

// Connect
    bool SocketObject::Connect(char* szServerAddress, int iPort)
   {
      struct		sockaddr_in serv_addr;
      LPHOSTENT	lphost;
   
      memset(&serv_addr,0,sizeof(sockaddr_in));
      serv_addr.sin_family = AF_INET;
      serv_addr.sin_addr.s_addr = inet_addr(szServerAddress);
   
      if (serv_addr.sin_addr.s_addr == INADDR_NONE)
      {
         lphost = gethostbyname(szServerAddress);
         if (lphost != NULL)
            serv_addr.sin_addr.s_addr = ((LPIN_ADDR)lphost->h_addr)->s_addr;
         else
         {
            WSASetLastError(WSAEINVAL);
            return FALSE;
         }
      }
   
      serv_addr.sin_port = htons(iPort);
   
   // Open the socket
      skSocket = socket(AF_INET, SOCK_STREAM, 0);
      if(skSocket == INVALID_SOCKET)
      {
         return false;
      }
   
      int err = connect(skSocket, (struct sockaddr*)&serv_addr,sizeof(sockaddr));
      if(err == SOCKET_ERROR)
      {
         Disconnect();
         return false;
      }
   
   
      stReceive.skSocket = skSocket;
      stReceive.szBuffer[0] = NULL;
      stReceive.iReadPos = 0;
      stReceive.iWritePos = 0;
      stReceive.iTerminate = 0;
   
   // Create the thread to receive data
      CreateThread(
         NULL,  // pointer to security attributes
         NULL,                         // initial thread stack size
         (LPTHREAD_START_ROUTINE ) &thrReceiveThread,     // pointer to thread function
         &stReceive,                        // argument for new thread
         NULL,                     // creation flags
         &dwReceiveHandle          // pointer to receive thread ID
         );
   
      return true;
   }

    void SocketObject::Disconnect()
   {
      if(skSocket != INVALID_SOCKET)
      {
         closesocket(skSocket);
         skSocket = INVALID_SOCKET;
      }
   }

    int SocketObject::Bind(int iPort)
   {
      sockaddr_in saServerAddress;
   
      skSocket = socket(AF_INET, SOCK_STREAM, 0);
   
      if(skSocket == INVALID_SOCKET)
      {
         return false;
      }
   
      memset(&saServerAddress, 0, sizeof(sockaddr_in));
   
      saServerAddress.sin_family = AF_INET;
      saServerAddress.sin_addr.s_addr = htonl(INADDR_ANY);
      saServerAddress.sin_port = htons(iPort);
   
      if( bind(skSocket, (sockaddr*) &saServerAddress, sizeof(sockaddr)) == SOCKET_ERROR)
      {
         Disconnect();
         return false;
      }
      else
         return true;
   }

    int SocketObject::Listen( void )
   {
      return listen( skSocket, 32 );
   }

    bool SocketObject::Accept( SocketObject &skAcceptSocket )
   {
      sockaddr_in saClientAddress;
      int			iClientSize = sizeof(sockaddr_in);
      SOCKADDR	IPAddress;
   
      skAcceptSocket.skSocket = accept( skSocket, (struct sockaddr*)&saClientAddress, &iClientSize );
   
      if( skAcceptSocket.skSocket == INVALID_SOCKET ) 
      {
         return false;
      }
      else 
      {
         memcpy(&IPAddress,&saClientAddress,sizeof(saClientAddress));
         printf("%d.%d.%d.%d is Connecting\n",saClientAddress.sin_addr.S_un.S_un_b.s_b1,saClientAddress.sin_addr.S_un.S_un_b.s_b2,saClientAddress.sin_addr.S_un.S_un_b.s_b3,saClientAddress.sin_addr.S_un.S_un_b.s_b4);
      
         skAcceptSocket.stReceive.skSocket = skAcceptSocket.skSocket;
         skAcceptSocket.stReceive.szBuffer[0] = NULL;
         skAcceptSocket.stReceive.iReadPos = 0;
         skAcceptSocket.stReceive.iWritePos = 0;
         skAcceptSocket.stReceive.iTerminate = 0;
      
      // Create the thread to receive data
         CreateThread(
            NULL,															// pointer to security attributes
            NULL,															// initial thread stack size
            (LPTHREAD_START_ROUTINE ) &skAcceptSocket.thrReceiveThread,     // pointer to thread function
            &skAcceptSocket.stReceive,              // argument for new thread
            NULL,									// creation flags
            &skAcceptSocket.dwReceiveHandle         // pointer to receive thread ID
            );
      
         return true;
      }
   }

    int SocketObject::Recv( char *szBuffer, int iBufLen, int iFlags)
   {
      return recv(skSocket, szBuffer, iBufLen, iFlags);
   }

    int SocketObject::Send(char *szBuffer, int iBufLen, int iFlags)
   {
      return send(skSocket,szBuffer,iBufLen,iFlags);
   }

    int SocketObject::iCalculateChecksum(stPacketHeader stHead)
   {
      int	iChecksum = 0;
   
      iChecksum = (stHead.iID+stHead.iLength+stHead.iType);
   
      return(iChecksum);
   }

That's all there is to it. The book mentions that in Visual Studio you need to link to the ws2_32.lib (which I think we have done)... so it must something else.
  #8  
Old 23-Feb-2006, 14:19
cable_guy_67's Avatar
cable_guy_67 cable_guy_67 is offline
Senior Member
 
Join Date: Oct 2004
Location: Nescopeck, PA
Posts: 1,109
cable_guy_67 is a jewel in the roughcable_guy_67 is a jewel in the roughcable_guy_67 is a jewel in the roughcable_guy_67 is a jewel in the rough

Re: G++ question...


Your code (with a few name changes) compiles with a number of warnings for me.

Code:
$ g++ -Wall socket_main.cpp socket_object.cpp -mno-cygwin -lws2_32 -s -o SocketTest socket_object.cpp: In member function `int SocketObject::vGetPacket(char*)': socket_object.cpp:35: warning: comparison between signed and unsigned integer expressions socket_object.cpp: In member function `bool SocketObject::Connect(char*, int)': socket_object.cpp:158: warning: converting to non-pointer type `char' from NULL socket_object.cpp:171: warning: passing NULL used for non-pointer converting 2 of `void* CreateThread(_SECURITY_ATTRIBUTES*, DWORD, DWORD (*)(void*), void*, DWORD, DWORD*)' socket_object.cpp:171: warning: passing NULL used for non-pointer converting 5 of `void* CreateThread(_SECURITY_ATTRIBUTES*, DWORD, DWORD (*)(void*), void*, DWORD, DWORD*)' socket_object.cpp: In member function `bool SocketObject::Accept(SocketObject&)': socket_object.cpp:234: warning: converting to non-pointer type `char' from NULL socket_object.cpp:247: warning: passing NULL used for non-pointer converting 2 of `void* CreateThread(_SECURITY_ATTRIBUTES*, DWORD, DWORD (*)(void*), void*, DWORD, DWORD*)' socket_object.cpp:247: warning: passing NULL used for non-pointer converting 5 of `void* CreateThread(_SECURITY_ATTRIBUTES*, DWORD, DWORD (*)(void*), void*, DWORD, DWORD*)'

Run
Code:
$ SocketTest ---------------------------------------------------- ConnectionTest Help ---------------------------------------------------- Usage: ConnectionTest [client/server] [ip,port/port] Example: ConnectionTest client 198.168.0.1 6000 Example: ConnectionTest server 6000

Mark
__________________
"Opportunity is missed by most people because it comes dressed in overalls and looks like work."
--Thomas Alva Edison
"Those who would give up essential liberty to purchase a little temporary safety, deserve neither liberty nor safety."
--Benjamin Franklin
"A happy person is not a person in a certain set of circumstances, but rather a person with a certain set of attitudes."
--Hugh Downs
  #9  
Old 23-Feb-2006, 14:30
TreyAU21's Avatar
TreyAU21 TreyAU21 is offline
Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 116
TreyAU21 has a spectacular aura aboutTreyAU21 has a spectacular aura about

Re: G++ question...


Yeah... I just got it working on my computer as well. To get it working over here, we simply had to change the order of arguments to g++... the -lws2_32 must be last.

This command build (with warnings, but no errors):
g++ -mno-cygwin ConnectionTest.cpp ../SocketObject/SocketObject.cpp -lws2_32

Before, I was putting the -l command before the source files. That changed everything. Just out of curiosity, what changes did you make to get it working?
  #10  
Old 24-Feb-2006, 07:36
cable_guy_67's Avatar
cable_guy_67 cable_guy_67 is offline
Senior Member
 
Join Date: Oct 2004
Location: Nescopeck, PA
Posts: 1,109
cable_guy_67 is a jewel in the roughcable_guy_67 is a jewel in the roughcable_guy_67 is a jewel in the roughcable_guy_67 is a jewel in the rough

Re: G++ question...


I created everything in a common directory and saved off your files with my normal naming convention. Nothing that changed anything you were doing.

As far as working, I think there is more to do.

It runs with no arguments passed but I was getting a crash when passing args in(progname client ip). If you have problems, let us know what you are using as test values.

Mark

BTW, I looked up the book you were talking about on Amazon. If I got it right, it sounds like you are going to run into quite a few problems with the source code. You may want to see if there is an updated source package at the publishers website. It may save you some headaches.
__________________
"Opportunity is missed by most people because it comes dressed in overalls and looks like work."
--Thomas Alva Edison
"Those who would give up essential liberty to purchase a little temporary safety, deserve neither liberty nor safety."
--Benjamin Franklin
"A happy person is not a person in a certain set of circumstances, but rather a person with a certain set of attitudes."
--Hugh Downs
 
 

Recent GIDBlogDeveloping GUIs with wxPython (Part 3) by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Borland compile question monnick C++ Forum 4 12-Feb-2006 17:40
non-member function question crq C++ Forum 1 03-Feb-2005 21:59
Simple question on arrays--please help! brookeville C++ Forum 16 17-Nov-2004 23:23
Repetition structure problem and question brookeville C++ Forum 17 29-Oct-2004 17:48
question of practice magiccreative C++ Forum 1 06-Feb-2004 07:17

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 18:26.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.