problemes de creation de sockets !

problemes de creation de sockets ! - C++ - Programmation

Marsh Posté le 20-08-2004 à 00:33:18    

salut tous le monde !!
 
je suis entrain de faire une appli qui doit marcher en reseau. j'utilise MFC et je dervie une classe de CAsnychSocket puis j'utilise un objet de cette classe derive ds une boite de dialogue pour etablir des connections client/serveur. le probleme c ke j'arrive pas a creer mes sockets, ni pour le client ni pour le serveur
 
voici le code pour le serveur :

Code :
  1. if (sock=NULL)
  2. {
  3.  delete sock;
  4.  sock=NULL;
  5. }
  6. sock=new CSock(this);
  7. sock->isserver=true;
  8. if( !sock->Create(4018))
  9. {
  10.  MessageBox("Erreur de création en tant que serveur ..." );
  11.  return;
  12. }
  13. psockD->Listen();


 
pour le client :
 

Code :
  1. sock = new CSock(this);
  2. sock->isclient=true;
  3. if(!sock->Create(4001))
  4.  {
  5.   MessageBox("erreur de creation en tant que client..." );
  6.   sock->Close();
  7.   return ;
  8.  }
  9.  if(addr.DoModal()==IDOK)
  10.  {
  11.   if(addr.Addr_name_ok)
  12.   {
  13.    sock->Connect(addr.adresse_name, 4018);


 
et a chaque tentaive : erreur de creation en tant que ...
sur un autre forum g vu qu'il faut mettre le code suivant ds la classe qui gere mon appli : CXyzApp  
[cpp]
 
BOOL CXyzApp::InitInstance()  
  {  
        if (!AfxSocketInit())  
        {  
              AfxMessageBox(IDP_SOCKETS_INIT_FAILED);  
              return FALSE;  
        }  
          ...  
          ...  
  }    
 
g essaye mais g le message suivant :
error C2065: 'IDP_SOCKETS_INIT_FAILED' : undeclared identifier
 
 
 
merci pour votre aide les gars...
 
 

Reply

Marsh Posté le 20-08-2004 à 00:33:18   

Reply

Marsh Posté le 20-08-2004 à 00:35:10    

if (sock=NULL)  
 
 
non mais merde ...

Reply

Marsh Posté le 20-08-2004 à 00:57:27    

non c if(sock !=NULL)
pardon c une erreur d'ecriture(cette erreur n'y est pas sur mon programme donc c pas la cause du probleme !)

Reply

Marsh Posté le 20-08-2004 à 01:01:35    

toutes façons delete se débrouille très bien avec des pointeurs nuls

Reply

Marsh Posté le 20-08-2004 à 11:08:14    

tiens, on a du mal avec les sockets?
j'ai pas retrouvé le site de socket mais vla son code:
jettes y un oeil.
 
client.cpp
//
// Client.cpp
//
// Extremely simple, stream client example.
// Works in conjunction with Server.cpp.
//
// The program attempts to connect to the server and port
// specified on the command line. The Server program prints
// the needed information when it is started. Once connected,
// the program sends data to the server, waits for a response
// and then exits.
//
// Compile and link with wsock32.lib
//
// Pass the server name and port number on the command line.  
//
// Example: Client MyMachineName 2000
//
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib" )
 
// Function prototype
void StreamClient(char *szServer, short nPort);
 
// Helper macro for displaying errors
#define PRINTERROR(s) \
  fprintf(stderr,"\n%: %d\n", s, WSAGetLastError())
 
////////////////////////////////////////////////////////////
 
void main(int argc, char **argv)
{
 WORD wVersionRequested = MAKEWORD(1,1);
 WSADATA wsaData;
 int nRet;
 short nPort;
 
 //
 // Check for the host and port arguments
 //
 if (argc != 3)
 {
  fprintf(stderr,"\nSyntax: client ServerName PortNumber\n" );
  return;
 }
 
 nPort = atoi(argv[2]);
 
 
 //
 // Initialize WinSock and check the version
 //
 nRet = WSAStartup(wVersionRequested, &wsaData);
 if (wsaData.wVersion != wVersionRequested)
 {  
  fprintf(stderr,"\n Wrong version\n" );
  return;
 }
 
 
 //
 // Go do the stuff a stream client does
 //
 StreamClient(argv[1], nPort);
 
 
 //
 // Release WinSock
 //
 WSACleanup();
}
 
////////////////////////////////////////////////////////////
 
void StreamClient(char *szServer, short nPort)
{
 printf("\nStream Client connecting to server: %s on port: %d",
    szServer, nPort);
 
 //
 // Find the server
 //
    LPHOSTENT lpHostEntry;
 
 lpHostEntry = gethostbyname(szServer);
    if (lpHostEntry == NULL)
    {
        PRINTERROR("gethostbyname()" );
        return;
    }
 
 //
 // Create a TCP/IP stream socket
 //
 SOCKET theSocket;
 
 theSocket = socket(AF_INET,    // Address family
        SOCK_STREAM,   // Socket type
        IPPROTO_TCP);  // Protocol
 if (theSocket == INVALID_SOCKET)
 {
  PRINTERROR("socket()" );
  return;
 }
 
 //
 // Fill in the address structure
 //
 SOCKADDR_IN saServer;
 
 saServer.sin_family = AF_INET;
 saServer.sin_addr = *((LPIN_ADDR)*lpHostEntry->h_addr_list);
          // ^ Server's address
 saServer.sin_port = htons(nPort); // Port number from command line
 
 //
 // connect to the server
 //
 int nRet;
 
 nRet = connect(theSocket,    // Socket
       (LPSOCKADDR)&saServer, // Server address
       sizeof(struct sockaddr));// Length of server address structure
 if (nRet == SOCKET_ERROR)
 {
  PRINTERROR("socket()" );
  closesocket(theSocket);
  return;
 }
 
while(true)
{
 //
 // Send data to the server
 //
 char szBuf[256];
 
 strcpy(szBuf, "From the Client" );
 nRet = send(theSocket,    // Connected socket
    szBuf,     // Data buffer
    strlen(szBuf),   // Length of data
    0);      // Flags
 if (nRet == SOCKET_ERROR)
 {
  PRINTERROR("send()" );
  closesocket(theSocket);
  return;
 }
 
 
 //
 // Wait for a reply
 //
 nRet = recv(theSocket,    // Connected socket
    szBuf,     // Receive buffer
    sizeof(szBuf),   // Size of receive buffer
    0);      // Flags
 if (nRet == SOCKET_ERROR)
 {
  PRINTERROR("recv()" );
  closesocket(theSocket);
  return;
 }
 
 
 //
 // Display the received data
 //
 printf("\nData received: %s", szBuf);
}
 
 closesocket(theSocket);
 return;
}
/*******************************************************************/
/*******************************************************************/
/*******************************************************************/
//
// Server.cpp
//
// Extremely simple, stream server example.
// Works in conjunction with Client.cpp.
//
// The program sets itself up as a server using the TCP
// protoocl. It waits for data from a client, displays
// the incoming data, sends a message back to the client
// and then exits.
//
// Compile and link with wsock32.lib
//
// Pass the port number that the server should bind() to
// on the command line. Any port number not already in use
// can be specified.
//
// Example: Server 2000
//
 
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib" )
// Function prototype
void StreamServer(short nPort);
 
// Helper macro for displaying errors
#define PRINTERROR(s) \
  fprintf(stderr,"\n%: %d\n", s, WSAGetLastError())
 
////////////////////////////////////////////////////////////
 
void main(int argc, char **argv)
{
 WORD wVersionRequested = MAKEWORD(1,1);
 WSADATA wsaData;
 int nRet;
 short nPort;
 
 //
 // Check for port argument
 //
 if (argc != 2)
 {
  fprintf(stderr,"\nSyntax: server PortNumber\n" );
  return;
 }
 
 nPort = atoi(argv[1]);
 
 //
 // Initialize WinSock and check version
 //
 nRet = WSAStartup(wVersionRequested, &wsaData);
 if (wsaData.wVersion != wVersionRequested)
 {  
  fprintf(stderr,"\n Wrong version\n" );
  return;
 }
 
 
 //
 // Do the stuff a stream server does
 //
 StreamServer(nPort);
 
 
 //
 // Release WinSock
 //
 WSACleanup();
}
 
////////////////////////////////////////////////////////////
 
void StreamServer(short nPort)
{
 //
 // Create a TCP/IP stream socket to "listen" with
 //
 SOCKET listenSocket;
 
 listenSocket = socket(AF_INET,   // Address family
        SOCK_STREAM,  // Socket type
        IPPROTO_TCP);  // Protocol
 if (listenSocket == INVALID_SOCKET)
 {
  PRINTERROR("socket()" );
  return;
 }
 
 
 //
 // Fill in the address structure
 //
 SOCKADDR_IN saServer;  
 
 saServer.sin_family = AF_INET;
 saServer.sin_addr.s_addr = INADDR_ANY; // Let WinSock supply address
 saServer.sin_port = htons(nPort);  // Use port from command line
 
 //
 // bind the name to the socket
 //
 int nRet;
 
 nRet = bind(listenSocket,    // Socket  
    (LPSOCKADDR)&saServer,  // Our address
    sizeof(struct sockaddr)); // Size of address structure
 if (nRet == SOCKET_ERROR)
 {
  PRINTERROR("bind()" );
  closesocket(listenSocket);
  return;
 }
 
 //
 // This isn't normally done or required, but in this  
 // example we're printing out where the server is waiting
 // so that you can connect the example client.
 //
 int nLen;
 nLen = sizeof(SOCKADDR);
 char szBuf[256];
 
 nRet = gethostname(szBuf, sizeof(szBuf));
 if (nRet == SOCKET_ERROR)
 {
  PRINTERROR("gethostname()" );
  closesocket(listenSocket);
  return;
 }
 
 //
 // Show the server name and port number
 //
 printf("\nServer named %s waiting on port %d\n",
   szBuf, nPort);
 
 //
 // Set the socket to listen
 //
 
 printf("\nlisten()" );
 nRet = listen(listenSocket,     // Bound socket
      SOMAXCONN);     // Number of connection request queue
 if (nRet == SOCKET_ERROR)
 {
  PRINTERROR("listen()" );
  closesocket(listenSocket);
  return;
 }
 
 //
 // Wait for an incoming request
 //
 SOCKET remoteSocket;
 
 printf("\nBlocking at accept()" );
 remoteSocket = accept(listenSocket,   // Listening socket
        NULL,     // Optional client address
        NULL);
 if (remoteSocket == INVALID_SOCKET)
 {
  PRINTERROR("accept()" );
  closesocket(listenSocket);
  return;
 }
 while(true){
 //
 // We're connected to a client
 // New socket descriptor returned already
 // has clients address
 
 //
 // Receive data from the client
 //
 memset(szBuf, 0, sizeof(szBuf));
 nRet = recv(remoteSocket,     // Connected client
    szBuf,       // Receive buffer
    sizeof(szBuf),     // Lenght of buffer
    0);        // Flags
 if (nRet == INVALID_SOCKET)
 {
  PRINTERROR("recv()" );
  closesocket(listenSocket);
  closesocket(remoteSocket);
  return;
 }
 
 //
 // Display received data
 //
 printf("\nData received: %s", szBuf);
 
 //
 // Send data back to the client
 //
 strcpy(szBuf, "From the Server" );
 nRet = send(remoteSocket,    // Connected socket
    szBuf,      // Data buffer
    strlen(szBuf),    // Lenght of data
    0);       // Flags
 
 //
 // Close BOTH sockets before exiting
 //
 }
 closesocket(remoteSocket);
 closesocket(listenSocket);
 return;
}

Reply

Marsh Posté le 20-08-2004 à 11:12:09    

merci pour ton code mais je dois bosser en C++ en utilisant les MFC et pas le langage C  
 

Reply

Marsh Posté le 21-08-2004 à 16:14:01    

ok mon probleme est resolu juste en mettant le code suivant dans classe application :
 

Code :
  1. BOOL CXyzApp::InitInstance() 
  2.   { 
  3.         if (!AfxSocketInit()) 
  4.         { 
  5.               AfxMessageBox("Erreur de creation..." ); 
  6.               return FALSE
  7.         } 
  8.           ... 
  9.           ... 
  10.   }


 
par contre j'ai un autre probleme. en effet quand j'ouvre deux fenetres de mon application pour tester si il ya connection entre les deux en utilisant le 127.0.0.1 il ya erreur de connection et g le message suivant : debug assertion failed.....file sockcore.cpp ...et il me demande de reessayer ou abondonner !!!  
mais quand je test mon application sur un reseau local tous marche bien !!
 
merçi
 
 

Reply

Marsh Posté le 23-08-2004 à 13:24:53    

quelqun a une solution ?
 
merci

Reply

Marsh Posté le 23-08-2004 à 16:25:14    

ben tu regardes le fichier sockcore.cpp, et tu cherches l'endroit où l'assertion échoue

Reply

Marsh Posté le 23-08-2004 à 17:49:07    

le probleme est dans la fonction :
 

Code :
  1. void PASCAL CAsyncSocket::DoCallBack(WPARAM wParam, LPARAM lParam)
  2. {
  3. if (wParam == 0 && lParam == 0)
  4.  return;
  5. // Has the socket be closed?
  6. CAsyncSocket* pSocket = CAsyncSocket::LookupHandle((SOCKET)wParam, TRUE);
  7. // If yes ignore messag
  8. if (pSocket != NULL)
  9.  return;
  10. pSocket = CAsyncSocket::LookupHandle((SOCKET)wParam, FALSE);
  11. if (pSocket == NULL)
  12. {
  13.  // Must be in the middle of an Accept call
  14.  pSocket = CAsyncSocket::LookupHandle(INVALID_SOCKET, FALSE);
  15.  ASSERT(pSocket != NULL);
  16.  pSocket->m_hSocket = (SOCKET)wParam;
  17.  CAsyncSocket::DetachHandle(INVALID_SOCKET, FALSE);
  18.  CAsyncSocket::AttachHandle(pSocket->m_hSocket, pSocket, FALSE);
  19. }
  20. int nErrorCode = WSAGETSELECTERROR(lParam);
  21. switch (WSAGETSELECTEVENT(lParam))
  22. {
  23. case FD_READ:
  24.  {
  25.   DWORD nBytes;
  26.   if (!pSocket->IOCtl(FIONREAD, &nBytes))
  27.    nErrorCode = WSAGetLastError();
  28.   if (nBytes != 0 || nErrorCode != 0)
  29.    pSocket->OnReceive(nErrorCode);
  30.  }
  31.  break;
  32. case FD_WRITE:
  33.  pSocket->OnSend(nErrorCode);
  34.  break;
  35. case FD_OOB:
  36.  pSocket->OnOutOfBandData(nErrorCode);
  37.  break;
  38. case FD_ACCEPT:
  39.  pSocket->OnAccept(nErrorCode);
  40.  break;
  41. case FD_CONNECT:
  42.  pSocket->OnConnect(nErrorCode);
  43.  break;
  44. case FD_CLOSE:
  45.  pSocket->OnClose(nErrorCode);
  46.  break;
  47. }
  48. }


 
et c'est au niveau de(le debug met une fleche) :
 
 ASSERT(pSocket != NULL);
merci


Message édité par didus00 le 23-08-2004 à 17:53:02
Reply

Sujets relatifs:

Leave a Replay

Make sure you enter the(*)required information where indicate.HTML code is not allowed