IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Langage C++ Discussion :

Server connecté a un client spécifique


Sujet :

Langage C++

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Inscrit en
    Mars 2010
    Messages
    62
    Détails du profil
    Informations personnelles :
    Âge : 36

    Informations forums :
    Inscription : Mars 2010
    Messages : 62
    Par défaut Server connecté a un client spécifique
    Bonjour a tous,

    Je m'explique: j'aimerais creer un server qui sera nefaite une passerelle entre un client de type TCP/Ip et un port com, sont but sera d'envoyé les donnée de l'un vers l'autre.

    Pour ce faire je dois utiliser se shéma:
    -Ecouter ethernet pendant 50ms
    Si il y a des donnees==>ENvoyé les donnée
    Sinon passer a la suite
    -Ecouter port com pendant 50ms
    Si il y a des donnees==>ENvoyé les donnée
    Sinon retourner au début jusqu'a deconnexion

    Je ne dois pas utiliser de thread mon programme doit alterner les phase d'écoute.

    Problème c'est que lorsque mon server (tout simple) se connect a un client il n'envoi et ne recois que des données de ce client même si l'autre arrive a se connecter.

    Je ne sais pas si j'ai bien était explicite.

    Mais en gros je ne sais pas comment un server peut s'adresser a un client spécifique et changer (j'ai l'adresse ip de la connexion ethernet et le port com sur lequel je doi envoyer des données).

    Voila.

    Merci.

    Bonne journée!

  2. #2
    Membre Expert Avatar de fregolo52
    Homme Profil pro
    Développeur C
    Inscrit en
    Août 2004
    Messages
    2 366
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur C

    Informations forums :
    Inscription : Août 2004
    Messages : 2 366
    Par défaut
    Citation Envoyé par LiaGalanodel Voir le message

    Problème c'est que lorsque mon server (tout simple) se connect a un client il n'envoi et ne recois que des données de ce client même si l'autre arrive a se connecter.

    Je ne sais pas si j'ai bien était explicite.
    je ne vois pas comment un 2e client peut se connecter si tu es en mono thread.

    je n'ai pas tout compris. peux-tu nous montrer un peu de ton code ?

  3. #3
    Membre confirmé
    Inscrit en
    Mars 2010
    Messages
    62
    Détails du profil
    Informations personnelles :
    Âge : 36

    Informations forums :
    Inscription : Mars 2010
    Messages : 62
    Par défaut
    Code main:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    /*
     * server.cpp
     *
     *  Created on: 18 mars 2010
     */
     
    #include <arpa/inet.h>
    #include <netdb.h>
    #include <sys/epoll.h>
    #include <netinet/in.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <errno.h>
    #include <unistd.h>
    #include <fcntl.h>
    #include <string>
    #include <iostream>
    #include "serverfunction.h"
     
     
    using namespace std;
    int main (void)
     
    {
    	SocketServer sockServ;	//Instanter class
    	std::string BUFFER_SERVER;
    	try
    	{
    		BUFFER_SERVER=0x46;
     
    		if (sockServ.InitSocketServer("172.28.5.62", 2000)!=false)
    		{
     
    				string l="Hello I'm the Server";
    				string r= sockServ.ReceiveLineServer();//Declaration of r which is equal to the Receive Line
    				cout << "I received: " << r << endl;
    				if (r.empty())
    					{
    					cout<<"Error in the send function of the client"<<endl;
    					}
    				cout<<"I send: "<<l<<endl;
    				sockServ.SendlineServer(l); //Function SendLine: send line: Hello
    				string b= sockServ.ReceiveLineServer();
    				if (b.empty())
    				{
    				throw Error(9,"MAIN: The buffer is empty, the Server don't receive the data send by the Client",2);;
    				}
    				cout << "I received: " << b << endl;
    				cout << "I send: " << BUFFER_SERVER << endl;
    				sockServ.SendlineServer(BUFFER_SERVER);
    		}
    		else
    		{
    			   cout<<"ERROR MAIN: Problem in the connection"<<endl;
    		}
     
    	}
     
    	catch(const std::exception& e)
    	{
    		std::cerr << "ERROR : " << e.what() << std::endl;
    	}
    	sockServ.CloseSocketServer();
    }
    Code socket.h
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    /*
     * serverfunction.h
     *
     *  Created on: 18 mars 2010
     */
     
    #ifndef SERVERFUNCTION_H_
    #define SERVERFUNCTION_H_
     
    #include <string>
     
    using namespace std;
     
    class SocketServer
    {
    public:
    	int SocketServerCon, SocketServerListen, ClientAdress;
    	bool InitSocketServer(const char* Address, int Port);
        void CloseSocketServer();
        //SEND AND RECIVE LINE
        void   SendBytesServer(const std::string&);
        void SendlineServer(std::string);
        std::string ReceiveBytesServer();
        std::string ReceiveLineServer();
    };
     
     
     
    class HMP_MicroSleepServer
    {
    public:
        HMP_MicroSleepServer(int TEMPO_USEC_CNX_TRY);
    };
     
     
     
    class Error: public std::exception
    {
    public:
        Error(int numero=0, const std::string& phrase="", int niveau=0) throw()
             :m_numero(numero),m_phrase(phrase),m_niveau(niveau)
        {}
     
         virtual const char* what() const throw()
         {
             return m_phrase.c_str();
         }
     
         int getNiveau() const throw()
         {
              return m_niveau;
         }
     
        virtual ~Error() throw()
        {}
     
    private:
        int m_numero;               // Numéro de l'erreur.
        std::string m_phrase;       // Description de l'erreur.
        int m_niveau;               // Niveau de l'erreur.
    };
     
    #endif /* SERVERFUNCTION_H_ */
    Code socket.cpp
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    /*
     * serverfunction.cpp
     *
     *  Created on: 18 mars 2010
     */
     
    #include <arpa/inet.h>
    #include <netdb.h>
    #include <sys/epoll.h>
    #include <netinet/in.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <errno.h>
    #include <unistd.h>
    #include <fcntl.h>
    #include <string>
    #include <iostream>
    #include "serverfunction.h"
     
    using namespace std;
     
    //SOCKET SERVER
    bool SocketServer::InitSocketServer(const char * Address, int Port)
    {
     
    	bool CreateSocket = false;
        struct sockaddr_in SocketServerParam,
    					   SocketClientParam;
     
        // Configure a socket server  in connected mode...
        SocketServerListen = socket(AF_INET, SOCK_STREAM, 0);
        if (SocketServerListen == -1)
        {
        	throw Error(1,"Problem in the creation of the socket",2);
        }
        else
        {
        	cout<<"Socket Server is correctly create"<<endl;
        	memset(&SocketServerParam, 0, sizeof (struct sockaddr_in)) ;
        	/*Set the first numbyte of the block memory pointed by ptr to the specified value (ptr, value to be set, number of bytes to be set to the value)*/
        	SocketServerParam.sin_family = AF_INET;
            // ...on specified address and port...
        	SocketServerParam.sin_port = htons(Port) ; //Port
        	SocketServerParam.sin_addr.s_addr = inet_addr(Address) ; //Address IP
            if (SocketServerParam.sin_addr.s_addr == INADDR_NONE)
            {
            	throw Error(2,"Problem in the set a socket parameter structure with the IP address and port",2);
            }
            	else
            {
            	/* bind the socket to the Internet address */
                if (bind(SocketServerListen, (struct sockaddr *)&SocketServerParam, sizeof(struct sockaddr_in)) == -1)
                {
                	throw Error(3,"Problem to bind the socket to the Internet Address",2);
                }
                else
                {
                    // Allow IP address immediate reuse
                    int flagReuseAddress = 1;
                    if (setsockopt(SocketServerListen, SOL_SOCKET, SO_REUSEADDR,
                        &flagReuseAddress, sizeof (int)) == -1)
                    {
                    	throw Error(4,"Problem to allow IP address",2);
                    }
                    else
                    {
                    	// ...for one client
    					if (listen(SocketServerListen,2) == -1)
    					{
    						throw Error(5,"Problem to prepare and accept the connection",2);
    					}
    					else
    					{
    						cout<<"Listen and wait a client"<<endl;
     
                    	// Initialize SocketServerCon variable
    					socklen_t ClientAdress=sizeof(SocketClientParam);
     
    					SocketServerCon = accept(SocketServerListen, (struct sockaddr *)&SocketClientParam, &ClientAdress);
     
    						if (SocketServerCon == -1)
    						{
    							cout<<"Problem in the accept function"<<endl;
    							//throw Error(5,"Problem to connect with the client",2);
    						}
    						else
    						{
    							cout<<"The connection is established with the client"<<endl;
    							// The connection is established with the client
    							CreateSocket = true;
     
    						}
     
    					}
     
                    }
     
                }
     
            }
     
        }
     
    return CreateSocket;
     
    }
     
    //CLOSE SOCKET
    void SocketServer::CloseSocketServer()
    {
    	close(SocketServerListen);
    	cout<<"Close the socket Server"<<endl;
    }
     
     
    //TEMPO
    HMP_MicroSleepServer::HMP_MicroSleepServer(int TEMPO_USEC_CNX_SERV)
    {
    sleep(TEMPO_USEC_CNX_SERV);
    }
     
    //RECEIVE AND SEND LINE
    void SocketServer::SendlineServer(string s)
    {
    	s += '\n';
    	if (send(SocketServerCon, s.c_str(), s.length(), 0)==-1)
    	{
    		throw Error(6,"Error in the send line server function",2);
    	}
    }
    std::string SocketServer::ReceiveLineServer()
    {
     
    	fd_set input_set; // Create Input set
    	int s;
    	struct timeval timeout;
    	timeout.tv_sec = 10; // Attends 50 msec pour returner.
    	timeout.tv_usec = 0;
    	string ret;
     
    	while (1){
    	 //Set up the input,and exception sets for select().
    	 FD_ZERO(&input_set);
    	 FD_SET(SocketServerCon, &input_set);
    	 s = select(SocketServerCon+1, &input_set, NULL, NULL,&timeout);
    	 if (s) // Is there data coming in?
    	 {
    	  // tu fais un recv.
     
    			while (1)
    			{
    				char r;
     
    				switch (recv(SocketServerCon, &r, 1, 0))
    				{
    				case 0: // not connected anymore but last line sent might not end in \n so return ret anyway.
    					return ret;
    				case -1:
    					return "";
    				throw Error(7,"Error in the receive line server function",2);
    				}
     
    				ret += r;
    				if (r == '\n')
     
    					return ret;
    			}
    	 }
    	 if (s == -1)
    	 {
    	   throw Error(12,"Error in the receive line server function(select function)",2);
    	 }
    	 if (s == 0)
    	 cout<<"No data coming in"<<endl;
    	 ret =0x48;
    	  return ret;
    	}
     
    }
    listen(SocketServerListen,2) ==>2 client peuvent se connecter

  4. #4
    Membre Expert Avatar de fregolo52
    Homme Profil pro
    Développeur C
    Inscrit en
    Août 2004
    Messages
    2 366
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur C

    Informations forums :
    Inscription : Août 2004
    Messages : 2 366
    Par défaut
    une appli monothread n'accepte qu'un seul client.

    Si tu regardes le sequencement de ton programme tu verras qu'on passe une seule fois par accept, donc tu n'auras qu'un seul client de connecté au serveur.

    Sinon, on regardant vite fait, ton code ne parrait pas déconnant !!!

    le client est sur le meme PC que le serveur ? Si non, tu peux tenter d'utiliser ethereal pour voir si des infos transitent entre les 2 process.

    Peux-tu mettre le contenu de la consoles pour voir les traces affichées ?

  5. #5
    gl
    gl est déconnecté
    Rédacteur

    Homme Profil pro
    Inscrit en
    Juin 2002
    Messages
    2 165
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Juin 2002
    Messages : 2 165
    Par défaut
    Citation Envoyé par fregolo52 Voir le message
    une appli monothread n'accepte qu'un seul client.
    Pas forcément. C'est justement un des usages de select().

  6. #6
    Membre confirmé
    Inscrit en
    Mars 2010
    Messages
    62
    Détails du profil
    Informations personnelles :
    Âge : 36

    Informations forums :
    Inscription : Mars 2010
    Messages : 62
    Par défaut
    Sinon, on regardant vite fait, ton code ne parrait pas déconnant !!!
    J'avou que je ne compren pas très bien ce que tu veu dire par là.

    En tout cas comme on peut voir dans l'essai que j'ai effectué les deux clients arrivent a se connecter mais le client numéro1 ne peut envoyer des fichiers.

    Mais ma question était plus sur le fait de: est ce que l'on peut se connecter a un client spécifique?
    Images attachées Images attachées  

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. probleme de connection serveur C client java
    Par ricardvince dans le forum Entrée/Sortie
    Réponses: 5
    Dernier message: 03/11/2006, 14h38
  2. Réponses: 5
    Dernier message: 30/08/2006, 15h29
  3. Acceder à sql server 2005 via un client léger
    Par N_ma dans le forum MS SQL Server
    Réponses: 3
    Dernier message: 16/05/2006, 13h53
  4. Réponses: 4
    Dernier message: 05/05/2006, 15h45
  5. [JDBC][SQL Server]Connection Pooling
    Par WE dans le forum JDBC
    Réponses: 4
    Dernier message: 14/03/2006, 09h15

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo