Forum |  HardWare.fr | News | Articles | PC | S'identifier | S'inscrire | Shop Recherche
2985 connectés 

  FORUM HardWare.fr
  Programmation

  Explications socket et thread SVP

 


 Mot :   Pseudo :  
 
Bas de page
Auteur Sujet :

Explications socket et thread SVP

n°97234
shinji
Posté le 06-02-2002 à 11:49:46  profilanswer
 

Voilà, j'essaye de faire un chat avec des sockets.
Pour l'instant j'ai fait un serveur et un client. Lorsqu'un client se connecte, le serveur crée un socket et lui envoi l'heure.
Mais je me pose bcp de questions:
 
- Est-ce que le serveur doit ensuite fermer ce socket et en ouvrir un à chaque fois qu'un client fait une requète ou est-ce que c'est une fois au départ et on la garde dans que le client n'a pas finit ou un certain temps ?
- Le serveur doit stocker les sockets créé mais comment fait-il pour écouter les demandes de connexions et répondre aux client déjà connectés?
- Je devrais utiliser les threads. Vois pas concrètement à quoi ils servent.
- On m'a dit que je devrais utiliser le mode asynchrone parce que j'aurais bcp de socket mais comment ça marche (je crois que c'est pour ne pas bloquer le serveur sur un client mais je comprend même pas bien pourquoi il se bloquerais ?)
 
J'ai cherché pourtant des infos mais je trouve que des exemples qui sont pour moi incomprehensible pour l'instant.
 
Je recherche quelqu'un qui pourraît m'expliquer simplement?
 
merci

mood
Publicité
Posté le 06-02-2002 à 11:49:46  profilanswer
 

n°97302
wpk
Posté le 06-02-2002 à 13:20:29  profilanswer
 

Citation :

- Est-ce que le serveur doit ensuite fermer ce socket et en ouvrir un à chaque fois qu'un client fait une requète ou est-ce que c'est une fois au départ et on la garde dans que le client n'a pas finit ou un certain temps ?  


 
Vaut mieux garder la meme socket un certain temps (ca economise un peu de bande passante et tmps cpu)
 

Citation :

- Le serveur doit stocker les sockets créé mais comment fait-il pour écouter les demandes de connexions et répondre aux client déjà connectés?  


T'est en quel langage :  
  Si java alors
    utilise les threads, tu associe à chaque client un thread dont le seul boulot c'est d'ecouter la socket avec son client.
  sinon si c/c++
    Si tu peux utiliser les threads, utilise les
    sinon regarde la doc du select (tu ecoutes plusieurs sock en meme temps)
 
 

Citation :

- Je devrais utiliser les threads. Vois pas concrètement à quoi ils servent.  
- On m'a dit que je devrais utiliser le mode asynchrone parce que j'aurais bcp de socket mais comment ça marche (je crois que c'est pour ne pas bloquer le serveur sur un client mais je comprend même pas bien pourquoi il se bloquerais ?)  


Un thread, c'est un chemin d'execution en parallele avec ton chemin d'exec principal. Du coup, si tu bloque dans un thread sur un read ou write sur une socket, ton interface graphique et tout le reste continue à s'executer et le thread socket se debloque tout seul lorsqu'un event rez se produit sur ta socket...
Ensuite faut voir combien de clients vont se connecter à ton serveur. S'il y en a vraiement bcp, vaut mieux utiliser le select qui consome bcp moins de ressources sys que les threads.

n°97358
shinji
Posté le 06-02-2002 à 14:43:52  profilanswer
 

merci!
 
Les select c'est pour le mode asynchrone c'est ça ?
Pourquoi est-ce moins gourmand en ressources ?
Comment ça marche?

n°97419
wpk
Posté le 06-02-2002 à 16:10:49  profilanswer
 

pour le select  :ange: RTFM :ange: :D  
 
quant à savoir pkoi les threads c'est plus lourd qu'un simple select, lit un peu de doc sur comment un systeme d'exploitation gere les threads et tu comprendras tout de suite...

n°97431
cvince
Posté le 06-02-2002 à 16:26:55  profilanswer
 

wpk a écrit a écrit :

pour le select  :ange: RTFM :ange: :D  




 :D

n°97441
shinji
Posté le 06-02-2002 à 16:40:20  profilanswer
 

Voilà l'algo si j'ai bien compris:
 
Serveur
 
Boucle "infinie"
{
-attente connection
-demande de connection{
       -création d'un socket
       -ajout du socket à la liste des clients
       -création d'un thread pour écouter le client
        (Chaque thread créé écoute le client et lorsque celui-ci  
         se manifeste, le thread envoi le message à tous les  
         autres clients.)
}
Serveur
 
 
-demande de création d'un socket
-création d'un thread qui écoute le serveur
        (Le thread créé écoute le serveur et lorsque celui-ci  
         se manifeste, le thread affiche le message au client.)
boucle tant que l'utilisateur le veut
{
-attendre que le client tape un message
-on envoi ce message au serveur
}
 
De cette façon, le serveur est bloqué sur les attentes de connection, c'est normal non, il n'a rien d'autre à faire puisque les threads s'occupent d'écouter les clients ?
Qu'est-ce  que change l'asynchrone dans mon algo, je vois pas?(enfin je dois pas comprendre quoi!)
Merci d'avance!

n°97444
shinji
Posté le 06-02-2002 à 16:41:03  profilanswer
 

PARDON, Petite erreur.
 
Voilà l'algo si j'ai bien compris:
 
Serveur
 
Boucle "infinie"
{
-attente connection
-demande de connection{
       -création d'un socket
       -ajout du socket à la liste des clients
       -création d'un thread pour écouter le client
        (Chaque thread créé écoute le client et lorsque celui-ci  
         se manifeste, le thread envoi le message à tous les  
         autres clients.)
}
Client
 
 
-demande de création d'un socket
-création d'un thread qui écoute le serveur
        (Le thread créé écoute le serveur et lorsque celui-ci  
         se manifeste, le thread affiche le message au client.)
boucle tant que l'utilisateur le veut
{
-attendre que le client tape un message
-on envoi ce message au serveur
}
 
De cette façon, le serveur est bloqué sur les attentes de connection, c'est normal non, il n'a rien d'autre à faire puisque les threads s'occupent d'écouter les clients ?
Qu'est-ce  que change l'asynchrone dans mon algo, je vois pas?(enfin je dois pas comprendre quoi!)
Merci d'avance!

n°97446
shinji
Posté le 06-02-2002 à 16:41:34  profilanswer
 

comprend pas, désolé  

wpk a écrit a écrit :

pour le select  :ange: RTFM :ange: :D  
 
quant à savoir pkoi les threads c'est plus lourd qu'un simple select, lit un peu de doc sur comment un systeme d'exploitation gere les threads et tu comprendras tout de suite...  



n°97482
wpk
Posté le 06-02-2002 à 17:46:28  profilanswer
 

commonçons par le plus simple :D
 

Citation :

comprend pas, désolé  


 
le RTFM est une expression courramant utilisé, pour indiquer poliment  :D  d'aller lire la doc (Read The Fu**ing Manual) :p
 
Les algos sont bons.  
 

Citation :

Qu'est-ce  que change l'asynchrone dans mon algo, je vois pas?(enfin je dois pas comprendre quoi!)


Tes algos, pour moi, (c'est pas forcement une reference) c'est de l'asynchro meme si c'est discutable vu que dans chaqun de tes threads t'es synchrone (tu bloque sur les primitives rezo jusqu'à l'obtention d'une reponse).

n°97536
shinji
Posté le 06-02-2002 à 18:52:20  profilanswer
 

ok je veux bien lire mais quel manuel ?

mood
Publicité
Posté le 06-02-2002 à 18:52:20  profilanswer
 

n°97540
shinji
Posté le 06-02-2002 à 18:59:25  profilanswer
 

merci en tout cas!

n°97562
wpk
Posté le 06-02-2002 à 19:24:48  profilanswer
 

sous linux : man -s 3c select  
sous windows : la msdn  
aller, je fournis le sav complet et je te file la compie de l'article de la msdn :) (sous nux c'est quasiment identique, la declaration de la fonction tout du moins est la meme)
 

Citation :


The Windows Sockets select function determines the status of one or more sockets, waiting if necessary, to perform synchronous I/O.
 
int select (
  int nfds,                            
  fd_set FAR * readfds,                
  fd_set FAR * writefds,              
  fd_set FAR * exceptfds,              
  const struct timeval FAR * timeout  
);
 
Parameters
nfds  
[in] This parameter is ignored; it is included only for compatibility with Berkeley sockets.  
readfds  
[in/out] An optional pointer to a set of sockets to be checked for readability.  
writefds  
[in/out] An optional pointer to a set of sockets to be checked for writability  
exceptfds  
[in/out] An optional pointer to a set of sockets to be checked for errors.  
timeout  
[in] The maximum time for select to wait, or NULL for blocking operation.  
Remarks
The select function is used to determine the status of one or more sockets. For each socket, the caller can request information on read, write or error status. The set of sockets for which a given status is requested is indicated by an FD_SET structure. The sockets contained within the FD_SET structures must be associated with a single service provider. For the purpose of this restriction, sockets are considered to be from the same service provider if the WSAPROTOCOL_INFO structures describing their protocols have the same providerId value. Upon return, the structures are updated to reflect the subset of these sockets that meet the specified condition. The select function returns the number of sockets meeting the conditions. A set of macros is provided for manipulating an FD_SET structure. These macros are compatible with those used in the Berkeley software, but the underlying representation is completely different.
 
The parameter readfds identifies the sockets that are to be checked for readability. If the socket is currently in the listen state, it will be marked as readable if an incoming connection request has been received such that an accept is guaranteed to complete without blocking. For other sockets, readability means that queued data is available for reading such that a call to recv, WSARecv, WSARecvFrom, or recvfrom is guaranteed not to block.
 
For connection-oriented sockets, readability can also indicate that a request to close the socket has been received from the peer. If the virtual circuit was closed gracefully, and all data was received, then a recv will return immediately with zero bytes read. If the virtual circuit was reset, then a recv will complete immediately with an error code such as WSAECONNRESET. The presence of out-of-band data will be checked if the socket option SO_OOBINLINE has been enabled (see setsockopt).
 
The parameter writefds identifies the sockets that are to be checked for writability. If a socket is processing a connect call (nonblocking), a socket is writable if the connection establishment successfully completes. If the socket is not processing a connect call, writability means a send, sendto, or WSASendto are guaranteed to succeed. However, they can block on a blocking socket if the len parameter exceeds the amount of outgoing system buffer space available. It is not specified how long these guarantees can be assumed to be valid, particularly in a multithreaded environment.
 
The parameter exceptfds identifies the sockets that are to be checked for the presence of out-of-band data (see section DECnet Out-Of-band data for a discussion of this topic) or any exceptional error conditions.  
 
Important Out-of-band data will only be reported in this way if the option SO_OOBINLINE is FALSE. If a socket is processing a connect call (nonblocking), failure of the connect attempt is indicated in exceptfds (application must then call getsockopt SO_ERROR to determine the error value to describe why the failure occurred). This document does not define which other errors will be included.
 
Any two of the parameters, readfds, writefds, or exceptfds, can be given as NULL. At least one must be non-NULL, and any non-NULL descriptor set must contain at least one handle to a socket.
 
Summary: A socket will be identified in a particular set when select returns if:
 
readfds:  
 
If listen has been called and a connection is pending, accept will succeed  
Data is available for reading (includes OOB data if SO_OOBINLINE is enabled)  
Connection has been closed/reset/terminated  
writefds:  
 
If processing a connect call (nonblocking), connection has succeeded  
Data can be sent  
exceptfds:  
 
If processing a connect call (nonblocking), connection attempt failed  
OOB data is available for reading (only if SO_OOBINLINE is disabled)  
Four macros are defined in the header file WINSOCK2.H for manipulating and checking the descriptor sets. The variable FD_SETSIZE determines the maximum number of descriptors in a set. (The default value of FD_SETSIZE is 64, which can be modified by defining FD_SETSIZE to another value before including WINSOCK2.H.) Internally, socket handles in an FD_SET structure are not represented as bit flags as in Berkeley Unix. Their data representation is opaque. Use of these macros will maintain software portability between different socket environments. The macros to manipulate and check FD_SET contents are:  
 
FD_CLR(s, *set)  
Removes the descriptor s from set.  
FD_ISSET(s, *set)  
Nonzero if s is a member of the set. Otherwise, zero.  
FD_SET(s, *set)  
Adds descriptor s to set.  
FD_ZERO(*set)  
Initializes the set to the NULL set.  
The parameter timeout controls how long the select can take to complete. If timeout is a null pointer, select will block indefinitely until at least one descriptor meets the specified criteria. Otherwise, timeout points to a TIMEVAL structure that specifies the maximum time that select should wait before returning. When select returns, the contents of the TIMEVAL structure are not altered. If TIMEVAL is initialized to {0, 0}, select will return immediately; this is used to "poll" the state of the selected sockets. If select returns immediately, then the select call is considered nonblocking and the standard assumptions for nonblocking calls apply. For example, the blocking hook will not be called, and Windows Sockets will not yield.
 
Note The select function has no effect on the persistence of socket events registered with WSAAsyncSelect or WSAEventSelect.
 
Return Values
The select function returns the total number of socket handles that are ready and contained in the FD_SET structures, zero if the time limit expired, or SOCKET_ERROR if an error occurred. If the return value is SOCKET_ERROR, WSAGetLastError can be used to retrieve a specific error code.
 
Error Codes
WSANOTINITIALISED A successful WSAStartup must occur before using this function.  
WSAEFAULT The Windows Sockets implementation was unable to allocate needed resources for its internal operations, or the readfds, writefds, exceptfds, or timeval parameters are not part of the user address space.  
WSAENETDOWN The network subsystem has failed.  
WSAEINVAL The timeout value is not valid, or all three descriptor parameters were NULL.  
WSAEINTR A blocking Windows Socket 1.1 call was canceled through WSACancelBlockingCall.  
WSAEINPROGRESS A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.  
WSAENOTSOCK One of the descriptor sets contains an entry that is not a socket.  
 
 
QuickInfo
  Windows NT: Yes
  Windows: Yes
  Windows CE: Use version 1.0 and later.
  Header: Declared in winsock2.h.
  Import Library: Link with ws2_32.lib.
 
See Also
accept, connect, recv, recvfrom, send, WSAAsyncSelect, WSAEventSelect  
 


Aller à :
Ajouter une réponse
  FORUM HardWare.fr
  Programmation

  Explications socket et thread SVP

 

Sujets relatifs
[C/UNIX] lire un stream ouvert a partir d'un file descriptor de socket[Java] Comment faire un multi thread
Nombres prmier en C encore un truc SVP!???[Kylix] Creation de socket.....
[C++] Comment savoir si un client et toujours connecté à un socket ?[VB] probleme de socket
AIDEZ MOI SVPC++ et les thread
[DirectSound] Lire un fichier son, un exemple SVP ! 
Plus de sujets relatifs à : Explications socket et thread SVP


Copyright © 1997-2022 Hardware.fr SARL (Signaler un contenu illicite / Données personnelles) / Groupe LDLC / Shop HFR