Serveur/client sous windows en mode console (vc++,devcpp,borland)

Soyez le premier à donner votre avis sur cette source.

Vue 19 840 fois - Téléchargée 847 fois

Description

Compilé sous VC++6, DevCpp, Borland 5.5
(Sous DevCpp, ne pas oublier de rajouter dans les options du projet -lwsock32)

En mode console sous windows !
J'ai laissé les possibilités d'afficher les codes d'erreur (pratique pour le déboguage)
A mettre dans deux fichiers différents.

Lancer le serveur puis le client.

Source / Exemple :


///////////////////////////////////////////////////////////////////////////////////////////////////
// LE SERVEUR
// serveur.cpp

#include <iostream>
using namespace std ;
#include <stdlib.h>
#include <winsock.h>
#include <string.h>

#define PORT 15                        // Port arbitraire de communication

//#define DEBUG                        // Si vous voulez pouvoir afficher les codes d'erreur

void ErreurWSA();

void main()
{

	cout << "Serveur pret." << endl;

	WORD wVersionRequested;
	WSADATA wsaData;
	wVersionRequested = MAKEWORD(1, 1);
	if (WSAStartup(wVersionRequested, &wsaData))
	{
		cerr << "Erreur WSAStartup : " ;
		ErreurWSA();
		system("PAUSE") ;
		exit(1) ;
	}	

	
	SOCKET s;
	s = socket(AF_INET,SOCK_STREAM,0);
	if(s==INVALID_SOCKET)
	{
		cerr << "ERREUR SOCKET : ";
		ErreurWSA();
		system("PAUSE") ;
		exit(1) ;
	}
	else
		cout << "SOCKET : " << s << endl;

	
	struct sockaddr_in sain;
	sain.sin_family = AF_INET;
	sain.sin_port = htons(PORT);
	sain.sin_addr.s_addr = INADDR_ANY;

	if(bind(s, (struct sockaddr *) &sain, sizeof(struct sockaddr_in)) == SOCKET_ERROR) 
    {
		cerr << "ERREUR BIND : ";
		ErreurWSA();
		system("PAUSE") ;
		exit(1) ;
	}

	if (listen(s, 5)==SOCKET_ERROR) 
    {
		cerr << "ERREUR LISTEN : ";
		ErreurWSA();
		system("PAUSE") ;
		exit(1) ;
	}

	cout << "En attente de connection." << endl;

	SOCKET ns;
	struct sockaddr_in fsain;
	int fromlen = sizeof(struct sockaddr_in);
	ns = accept(s,(struct sockaddr *) &fsain, &fromlen);

	if(ns==SOCKET_ERROR)
	{
		cerr << "ERREUR ACCEPT : ";
		ErreurWSA();
		system("PAUSE") ;
		exit(1) ;
	}

	cout << "Connection avec le client etablie." << endl;

	char buffer[64];
	int rec;

	do
	{
		rec = recv(ns,buffer,64*sizeof(char),0); 
		buffer[rec] = '\0' ;
		cout << buffer << endl;
		memset(buffer, 0, 64*sizeof(char));
	
	}while(rec>0);

	cout << "Connection fermee par le client" << endl;

	if(closesocket(s)==SOCKET_ERROR)
	{
		cerr << "ERREUR CLOSE : ";
		ErreurWSA();
		system("PAUSE") ;
		exit(8) ;
	}		

	WSACleanup();

	cout << endl ;
	system("PAUSE");

}

#ifdef DEBUG
void ErreurWSA()
{
	int error = WSAGetLastError();

	switch(error)
	{
	case WSAEINTR:
		{
			cerr << "WSAEINTR" << endl;
			break;
		}
	case WSAEBADF:
		{
			cerr << "WSAEBADF" << endl;
			break;
		}
	case WSAEACCES:
		{
			cerr << "WSAEACCES" << endl;
			break;
		}
	case WSAEDISCON:
		{
			cerr << "WSAEDISCON" << endl;
			break;
		}
	case WSAEFAULT:
		{
			cerr << "WSAEFAULT" << endl;
			break;
		}
	case WSAEINVAL:
		{
			cerr << "WSAEINVAL" << endl;
			break;
		}
	case WSAEMFILE:
		{
			cerr << "WSAEMFILE" << endl;
			break;
		}
	case WSAEWOULDBLOCK:
		{
			cerr << "WSAEWOULDBLOCK" << endl;
			break;
		}
	case WSAEINPROGRESS:
		{
			cerr << "WSAEINPROGRESS" << endl;
			break;
		}
	case WSAEALREADY:
		{
			cerr << "WSAEALREADY" << endl;
			break;
		}
	case WSAENOTSOCK:
		{
			cerr << "WSAENOTSOCK" << endl;
			break;
		}
	case WSAEDESTADDRREQ:
		{
			cerr << "WSAEDESTADDRREQ" << endl;
			break;
		}
	case WSAEMSGSIZE:
		{
			cerr << "WSAEMSGSIZE" << endl;
			break;
		}
	case WSAEPROTOTYPE:
		{
			cerr << "WSAEPROTOTYPE" << endl;
			break;
		}
	case WSAENOPROTOOPT:
		{
			cerr << "WSAENOPROTOOPT" << endl;
			break;
		}
	case WSAEPROTONOSUPPORT:
		{
			cerr << "WSAEPROTONOSUPPORT" << endl;
			break;
		}
	case WSAESOCKTNOSUPPORT:
		{
			cerr << "WSAESOCKTNOSUPPORT" << endl;
			break;
		}
	case WSAEOPNOTSUPP:
		{
			cerr << "WSAEOPNOTSUPP" << endl;
			break;
		}
	case WSAEPFNOSUPPORT:
		{
			cerr << "WSAEPFNOSUPPORT" << endl;
			break;
		}
	case WSAEAFNOSUPPORT:
		{
			cerr << "WSAEAFNOSUPPORT" << endl;
			break;
		}
	case WSAEADDRINUSE:
		{
			cerr << "WSAEADDRINUSE" << endl;
			break;
		}
	case WSAEADDRNOTAVAIL:
		{
			cerr << "WSAEADDRNOTAVAIL" << endl;
			break;
		}
	case WSAENETDOWN:
		{
			cerr << "WSAENETDOWN" << endl;
			break;
		}
	case WSAENETUNREACH:
		{
			cerr << "WSAENETUNREACH" << endl;
			break;
		}
	case WSAENETRESET:
		{
			cerr << "WSAENETRESET" << endl;
			break;
		}
	case WSAECONNABORTED:
		{
			cerr << "WSAECONNABORTED" << endl;
			break;
		}
	case WSAECONNRESET:
		{
			cerr << "WSAECONNRESET" << endl;
			break;
		}
	case WSAENOBUFS:
		{
			cerr << "WSAENOBUFS" << endl;
			break;
		}
	case WSAEISCONN:
		{
			cerr << "WSAEISCONN" << endl;
			break;
		}
	case WSAENOTCONN:
		{
			cerr << "WSAENOTCONN" << endl;
			break;
		}
	case WSAESHUTDOWN:
		{
			cerr << "WSAESHUTDOWN" << endl;
			break;
		}
	case WSAETOOMANYREFS:
		{
			cerr << "WSAETOOMANYREFS" << endl;
			break;
		}
	case WSAETIMEDOUT:
		{
			cerr << "WSAETIMEDOUT" << endl;
			break;
		}
	case WSAECONNREFUSED:
		{
			cerr << "WSAECONNREFUSED" << endl;
			break;
		}
	case WSAELOOP:
		{
			cerr << "WSAELOOP" << endl;
			break;
		}
	case WSAENAMETOOLONG:
		{
			cerr << "WSAENAMETOOLONG" << endl;
			break;
		}
	case WSAEHOSTDOWN:
		{
			cerr << "WSAEHOSTDOWN" << endl;
			break;
		}
	case WSAEHOSTUNREACH:
		{
			cerr << "WSAEHOSTUNREACH" << endl;
			break;
		}
	case WSASYSNOTREADY:
		{
			cerr << "WSASYSNOTREADY" << endl;
			break;
		}
	case WSAVERNOTSUPPORTED:
		{
			cerr << "WSAVERNOTSUPPORTED" << endl;
			break;
		}
	case WSANOTINITIALISED:
		{
			cerr << "WSANOTINITIALISED" << endl;
			break;
		}
	case WSAHOST_NOT_FOUND:
		{
			cerr << "WSAHOST_NOT_FOUND" << endl;
			break;
		}
	case WSATRY_AGAIN:
		{
			cerr << "WSATRY_AGAIN" << endl;
			break;
		}
	case WSANO_RECOVERY:
		{
			cerr << "WSANO_RECOVERY" << endl;
			break;
		}
	case WSANO_DATA:
		{
			cerr << "WSANO_DATA" << endl;
			break;
		}
	default:
		{
			cerr << "Erreur inconnue" << endl;
			break;
		}
	}
}

#else //DEBUG
void ErreurWSA(){}

#endif //DEBUG

////////////////////////////////////////////////////////////////////////////////////////////////////
// LE CLIENT
// client.cpp

#include <iostream>
using namespace std;
#include <stdlib.h>
#include <winsock.h>
#include <string.h>

#define PORT 15                            // même port que le serveur

//#define DEBUG
void ErreurWSA();
void Syntaxe();

void main(int argc, char *argv[])
{
    if(argc<2||argc>3)
    {
        Syntaxe();
    }
	cout << "Client pret." << endl;

	WORD wVersionRequested;
	WSADATA wsaData;
	wVersionRequested = MAKEWORD(1, 1);
	if (WSAStartup(wVersionRequested, &wsaData))
	{
		cerr << "Erreur WSAStartup : ";
		ErreurWSA();
		system("PAUSE");
		exit(2);
	}
	
	
	
	SOCKET s;
	s = socket(AF_INET,SOCK_STREAM,0);
	if(s==INVALID_SOCKET)
	{
		cerr << "ERREUR SOCKET : ";
		ErreurWSA();
		system("PAUSE");
		exit(2);
	}
	else
		cout << "SOCKET : " << s << endl;

	struct sockaddr_in sain;
	sain.sin_family = AF_INET;
	sain.sin_port = htons(PORT);
	sain.sin_addr.s_addr = INADDR_ANY;

    if(!strcmp(argv[1],"-ip"))
    {
        cout << "Connection a " << argv[2] << endl;
	    sain.sin_addr.s_addr = inet_addr(argv[2]);
    }
    else
    {
    	struct hostent * host;
	    char FAR hostname[64];
        if(!strcmp(argv[1],"-host"))
        {
             cout << "Connection a " << argv[2] << endl;
             strcpy(hostname, argv[2]);
        }
        else if(!strcmp(argv[1],"-localhost"))
        {
        	gethostname(hostname, sizeof(hostname));
            cout << "Connection a " << hostname << endl;
        }
        else
        {
            Syntaxe();
        }
        host = gethostbyname(hostname);
        memcpy(&sain.sin_addr.s_addr, host->h_addr, host->h_length);
    }

	if(connect(s, (struct sockaddr *) &sain, sizeof(sain))==SOCKET_ERROR) 
    {
		cerr << "ERREUR CONNECT : ";
		ErreurWSA();
		system("PAUSE");
		exit(2);
	}

	cout << "Client connecte au serveur." << endl;
	cout << "\"close\" pour quitter." << endl;

	char clnt[64];
	strcpy(clnt,"Client connecte.");
	do
	{
		if(send(s, clnt, strlen(clnt), 0)==SOCKET_ERROR)
		{
			cerr << "ERREUR SEND : ";
			ErreurWSA();
			system("PAUSE");
			exit(2);
		}
		cout << "Envoye : " << clnt << endl << "# ";
		cin.getline(clnt,64,'\n');

	}while(strcmp(clnt,"close"));
	
	
	
	if(closesocket(s)==SOCKET_ERROR)
	{
		cerr << "ERREUR CLOSE : ";
		ErreurWSA();
		system("PAUSE") ;
		exit(2) ;
	}		

	WSACleanup();

	cout << endl ;
	system("PAUSE");

}

void Syntaxe()
{
     cout << "Syntaxe : client.exe [options]" << endl;
     cout << " -localhost\n -host NomDeLHote\n -ip \"AdresseIP\"\n" << endl;
     system("PAUSE");
     exit(1);
}  

#ifdef DEBUG
void ErreurWSA()
{
	int error = WSAGetLastError();

	switch(error)
	{
	case WSAEINTR:
		{
			cerr << "WSAEINTR" << endl;
			break;
		}
	case WSAEBADF:
		{
			cerr << "WSAEBADF" << endl;
			break;
		}
	case WSAEACCES:
		{
			cerr << "WSAEACCES" << endl;
			break;
		}
	case WSAEDISCON:
		{
			cerr << "WSAEDISCON" << endl;
			break;
		}
	case WSAEFAULT:
		{
			cerr << "WSAEFAULT" << endl;
			break;
		}
	case WSAEINVAL:
		{
			cerr << "WSAEINVAL" << endl;
			break;
		}
	case WSAEMFILE:
		{
			cerr << "WSAEMFILE" << endl;
			break;
		}
	case WSAEWOULDBLOCK:
		{
			cerr << "WSAEWOULDBLOCK" << endl;
			break;
		}
	case WSAEINPROGRESS:
		{
			cerr << "WSAEINPROGRESS" << endl;
			break;
		}
	case WSAEALREADY:
		{
			cerr << "WSAEALREADY" << endl;
			break;
		}
	case WSAENOTSOCK:
		{
			cerr << "WSAENOTSOCK" << endl;
			break;
		}
	case WSAEDESTADDRREQ:
		{
			cerr << "WSAEDESTADDRREQ" << endl;
			break;
		}
	case WSAEMSGSIZE:
		{
			cerr << "WSAEMSGSIZE" << endl;
			break;
		}
	case WSAEPROTOTYPE:
		{
			cerr << "WSAEPROTOTYPE" << endl;
			break;
		}
	case WSAENOPROTOOPT:
		{
			cerr << "WSAENOPROTOOPT" << endl;
			break;
		}
	case WSAEPROTONOSUPPORT:
		{
			cerr << "WSAEPROTONOSUPPORT" << endl;
			break;
		}
	case WSAESOCKTNOSUPPORT:
		{
			cerr << "WSAESOCKTNOSUPPORT" << endl;
			break;
		}
	case WSAEOPNOTSUPP:
		{
			cerr << "WSAEOPNOTSUPP" << endl;
			break;
		}
	case WSAEPFNOSUPPORT:
		{
			cerr << "WSAEPFNOSUPPORT" << endl;
			break;
		}
	case WSAEAFNOSUPPORT:
		{
			cerr << "WSAEAFNOSUPPORT" << endl;
			break;
		}
	case WSAEADDRINUSE:
		{
			cerr << "WSAEADDRINUSE" << endl;
			break;
		}
	case WSAEADDRNOTAVAIL:
		{
			cerr << "WSAEADDRNOTAVAIL" << endl;
			break;
		}
	case WSAENETDOWN:
		{
			cerr << "WSAENETDOWN" << endl;
			break;
		}
	case WSAENETUNREACH:
		{
			cerr << "WSAENETUNREACH" << endl;
			break;
		}
	case WSAENETRESET:
		{
			cerr << "WSAENETRESET" << endl;
			break;
		}
	case WSAECONNABORTED:
		{
			cerr << "WSAECONNABORTED" << endl;
			break;
		}
	case WSAECONNRESET:
		{
			cerr << "WSAECONNRESET" << endl;
			break;
		}
	case WSAENOBUFS:
		{
			cerr << "WSAENOBUFS" << endl;
			break;
		}
	case WSAEISCONN:
		{
			cerr << "WSAEISCONN" << endl;
			break;
		}
	case WSAENOTCONN:
		{
			cerr << "WSAENOTCONN" << endl;
			break;
		}
	case WSAESHUTDOWN:
		{
			cerr << "WSAESHUTDOWN" << endl;
			break;
		}
	case WSAETOOMANYREFS:
		{
			cerr << "WSAETOOMANYREFS" << endl;
			break;
		}
	case WSAETIMEDOUT:
		{
			cerr << "WSAETIMEDOUT" << endl;
			break;
		}
	case WSAECONNREFUSED:
		{
			cerr << "WSAECONNREFUSED" << endl;
			break;
		}
	case WSAELOOP:
		{
			cerr << "WSAELOOP" << endl;
			break;
		}
	case WSAENAMETOOLONG:
		{
			cerr << "WSAENAMETOOLONG" << endl;
			break;
		}
	case WSAEHOSTDOWN:
		{
			cerr << "WSAEHOSTDOWN" << endl;
			break;
		}
	case WSAEHOSTUNREACH:
		{
			cerr << "WSAEHOSTUNREACH" << endl;
			break;
		}
	case WSASYSNOTREADY:
		{
			cerr << "WSASYSNOTREADY" << endl;
			break;
		}
	case WSAVERNOTSUPPORTED:
		{
			cerr << "WSAVERNOTSUPPORTED" << endl;
			break;
		}
	case WSANOTINITIALISED:
		{
			cerr << "WSANOTINITIALISED" << endl;
			break;
		}
	case WSAHOST_NOT_FOUND:
		{
			cerr << "WSAHOST_NOT_FOUND" << endl;
			break;
		}
	case WSATRY_AGAIN:
		{
			cerr << "WSATRY_AGAIN" << endl;
			break;
		}
	case WSANO_RECOVERY:
		{
			cerr << "WSANO_RECOVERY" << endl;
			break;
		}
	case WSANO_DATA:
		{
			cerr << "WSANO_DATA" << endl;
			break;
		}
	default:
		{
			cerr << "Erreur inconnue" << endl;
			break;
		}
	}
}

#else //DEBUG
void ErreurWSA(){}

#endif //DEBUG

Codes Sources

A voir également

Ajouter un commentaire

Commentaires

Messages postés
16
Date d'inscription
mercredi 12 mars 2003
Statut
Membre
Dernière intervention
10 janvier 2007

Bien, moi j'ai une question, pour ajouter un client? est-ce que ce serait facile? (une conférence à trois !)
Messages postés
16
Date d'inscription
mercredi 12 mars 2003
Statut
Membre
Dernière intervention
10 janvier 2007

Ca fonctionne super bien, merci pour ton code...

MAXTOR2: Pour que ca marche, moi j'ai créé un nouveau projet (Win32 Console Application - Empty) dans Visual Studio 6, j'ai effacé le main.cpp et j'ai ajouter son fichier client.cpp et j'ai ajouter cette ligne:
#pragma comment( lib, "wsock32.lib" )
Messages postés
5
Date d'inscription
mardi 21 novembre 2006
Statut
Membre
Dernière intervention
30 novembre 2006

bonjour,
Moi j'ai juste une erreur:
line 16 error:'main' must return 'int'
devellopeur: code::block
pourtant j'ai inclut les fichier libwsock32.a!!
voila si quelqu'un pourrait m'aider, merci.
Messages postés
1
Date d'inscription
jeudi 3 août 2006
Statut
Membre
Dernière intervention
18 août 2006

Bonjour,

Je fais un test de connexion entre un client et un serveur sur un PDA (OS : WM5) en utilisant l'adresse de boucle locale ("127.0.0.1"). J'arrive à établir une connexion mais je récupere l'erreur WSAENOTSOCK lors de l'appel de la fonction send. ceci serait-il dû à l'OS ou à autre chose? merci de me communiquer vos solutions.

PS: je developpe sous Visual Studio 2005 qui est équivalent à eVC++ ou Visual C++
Messages postés
19
Date d'inscription
vendredi 17 décembre 2004
Statut
Membre
Dernière intervention
10 juillet 2006

ah c bon, j'ai trouvé client.Exe -localhost 96 ^^
Afficher les 18 commentaires

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.