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

Entrée/Sortie Java Discussion :

Serveur socket multi client qui bloque sur le premier client


Sujet :

Entrée/Sortie Java

  1. #1
    Membre du Club
    Inscrit en
    Août 2008
    Messages
    184
    Détails du profil
    Informations forums :
    Inscription : Août 2008
    Messages : 184
    Points : 49
    Points
    49
    Par défaut Serveur socket multi client qui bloque sur le premier client
    Bonjour,
    Je suis entrain de réaliser un serveur socket , qui doit réceptionner les requests client et répondre à leurs demandes.
    Mais mon serveur ne répond qu'au premier client , si je lance une deuxième socket client rien ne se passe.
    Je suis vraiment bloqué

    Voici mon code serveur :
    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
     
    package com.cit.xDR.test;
     
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.nio.charset.Charset;
    import java.util.HashMap;
    import java.util.Iterator;
     
    public class NIOEchoServer {
     
    	private ServerSocketChannel serverchannel ;
     
    	private Selector selector ;
     
    	private HashMap<SocketChannel,ByteBuffer> queuedWrites = new HashMap<SocketChannel,ByteBuffer>() ;
     
    	public static void main(String[] args) {
     
    		NIOEchoServer n = new NIOEchoServer() ;
     
    		n.run();
     
     
     
    	}
     
     
    	public void run() {
     
    		try {
     
    			serverchannel = ServerSocketChannel.open() ;
     
    			serverchannel.configureBlocking(false) ;
     
    			serverchannel.socket().bind(new InetSocketAddress("localhost",10081)); 
     
    			selector = Selector.open();
     
    			serverchannel.register(selector, SelectionKey.OP_ACCEPT) ;
     
    			while(true) {
    				try {
    					//System.out.println("Before Communicator");
    					//new Communicator(selector).start();
    					selector.select() ;
     
    					Iterator<SelectionKey> keysIterator = selector.selectedKeys().iterator() ;
     
    					while(keysIterator.hasNext()) {
     
    						SelectionKey key = keysIterator.next(); 
    						keysIterator.remove();
     
     
    						if (key.isAcceptable()) {
     
    							ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
    					         SocketChannel sc = ssc.accept();
    					         sc.configureBlocking( false );
    					         //Communicator com = new Communicator(key);
     
    					          sc.register( selector, SelectionKey.OP_READ);
    					         // com.start();
     
    						} 
    						else if (key.isReadable()) {
     
    							SocketChannel sc = (SocketChannel)key.channel();
    							ByteBuffer readBuffer = ByteBuffer.allocate(8192);
     
    							int numread ;
    							while (true) {
    					            // readBuffer.clear();
     
    					            numread = sc.read( readBuffer );
     
    					            if (numread <=0) {
    					              break;
    					            }
     
     
    					          }
     
    							if (numread == -1) {
    								// Remote entity shut the socket down cleanly. Do the
    								// same from our end and cancel the channel.
    								key.channel().close();
    								key.cancel();
    								continue ;
    							}
     
     
    							  System.out.println("Read :" + numread + " " + new String(readBuffer.array())) ;
     
    							  readBuffer.flip() ;
    							  queuedWrites.put(sc,readBuffer) ;	
    							  key.interestOps(SelectionKey.OP_WRITE) ;
     
    						} else if (key.isWritable()) {
     
    							SocketChannel sc = (SocketChannel)key.channel();
     
    							ByteBuffer towrite = queuedWrites.get(sc) ;
     
     
     
    							System.out.println("Echoing :" + new String(towrite.array())) ;
     
    							ByteBuffer resp = ByteBuffer.wrap("ACK".getBytes());
     
    							while (true) {
    								int n = sc.write(resp) ;
     
     
     
    								if (n == 0 || resp.remaining() == 0)
    									break ;
    							}	
     
    							key.interestOps(SelectionKey.OP_READ) ;
    						}
     
     
     
    					}
    				        } catch (Exception e) {
     
    				        }
     
    			}
     
     
     
    		} catch(IOException e) {
     
    			System.out.println(e) ;
    		}
    	}
     
    //	private void waitForCalls() throws IOException {
    //		new Communicator(selector).start();
    //	    }
     
     
     
    }
    Mon code client :
    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
     
    package com.cit.xDR.test;
     
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.ArrayDeque;
    import java.util.Deque;
    import java.util.Iterator;
     
    public class NIOEchoClient {
     
    	private SocketChannel clientChannel ;
     
    	private Selector selector ;
     
    	public Deque<String> writeQueue = new ArrayDeque<String>() ; 
     
    	private ByteBuffer readBuf = ByteBuffer.allocate(8192) ;
     
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		NIOEchoClient nm = new NIOEchoClient() ;
     
    		try {
     
    			nm.init() ;
    			nm.run(); 
     
    		} catch(IOException e) {
     
    			System.out.println(e) ;
    		}
     
     
    	}
     
     
    	public void init() throws IOException {
     
     
     
    		selector = Selector.open() ;
     
    		clientChannel = SocketChannel.open();
    	    clientChannel.configureBlocking(false);
     
    	    // Kick off connection establishment
    	    clientChannel.connect(new InetSocketAddress("localhost", 10081));
     
    	    clientChannel.register(selector, SelectionKey.OP_CONNECT) ;
     
    	}
     
    	public void run() {
     
    		int i = 0 ;
    		boolean done = false ;
     
    		try {
     
     
     
     
    		while(true) {
     
    			writeQueue.add("This is line " + i) ;
     
    			selector.select() ;
     
    			Iterator<SelectionKey> skeys = selector.selectedKeys().iterator() ;
     
    			while (skeys.hasNext()) {
    				SelectionKey key = (SelectionKey) skeys.next();
    				skeys.remove();
     
    				if (!key.isValid()) {
    					continue;
    				}
     
    				// Check what event is available and deal with it
    				if (key.isConnectable()) {
    					finishConnection(key);
    				} else if (key.isReadable()) {
    					read(key);
    					// done = true ;
    				} else if (key.isWritable()) {
    					write(key);
    				}
    			}
     
    			i++ ;
    			 if (i == 10)
    				break ;
    		}
     
    		} catch(IOException e) {
    			System.out.println(e) ;
    		}
     
    	}
     
    	private void finishConnection(SelectionKey key) throws IOException {
     
    		clientChannel.finishConnect() ;
    		key.interestOps(SelectionKey.OP_WRITE) ;
     
    	}
     
    	private void write(SelectionKey key) throws IOException {
     
    		String toWrite = writeQueue.pollFirst() ;
     
    		System.out.println("writing :" + toWrite) ;
     
    		if (toWrite != null) {
     
    			ByteBuffer b ;
    			b = ByteBuffer.wrap(toWrite.getBytes()) ;
     
    			// b.flip();
     
    			while (true) {
    				int n = clientChannel.write(b) ;
     
     
     
    				if (n == 0 || b.remaining() == 0)
    					break ;
    			}	
     
    		}
     
    		key.interestOps(SelectionKey.OP_READ) ;
    	}
     
    	public void read(SelectionKey key) throws IOException {
     
    		readBuf.clear() ;
     
    		while (true) {
                // readBuffer.clear();
     
                int numread = clientChannel.read( readBuf );
     
                if (numread <=0) {
                  break;
                }
     
     
              }
     
    		   System.out.println("Read Echo from server:" + new String(readBuf.array())) ;
     
     
     
    		key.interestOps(SelectionKey.OP_WRITE) ;
     
    	}
     
    }
    Si quelqu'un peut m'aider , je serais vraiment reconnaissant !

  2. #2
    Expert éminent sénior
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Points : 48 807
    Points
    48 807
    Par défaut
    Tu as une boucle infinie qui fais les opérations suivantes dans l'ordre

    prendre une connection (select)
    traiter toutes les demandes du client
    fermer la connection


    donc tu dois bien te dire qu'il est impossible de servir le deuxième client tant que le premier n'est pas déconnecté. Si tu veux servir plusieurs clients simultanément, il va falloir revoir ta logique:

    soit travailler en multi thread, et démarrer un nouveau thread pour chaque nouveau client
    soit revoir tous les code pour gérer chacunes des connection en parallèle et tenir compte des connection qui arrivent pendant que d'autres sont toujours actives.

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

Discussions similaires

  1. [Débutant] Scrollbar qui bloque sur un ListView
    Par Whombat dans le forum VB.NET
    Réponses: 13
    Dernier message: 22/11/2011, 22h32
  2. [AC-2003] dlookup qui bloque sur le premier enregistrement
    Par chuspyto dans le forum VBA Access
    Réponses: 2
    Dernier message: 14/02/2010, 09h37
  3. Réponses: 2
    Dernier message: 26/01/2008, 12h19
  4. [MySQL] texte qui bloque sur une requéte mysql
    Par leto02 dans le forum PHP & Base de données
    Réponses: 2
    Dernier message: 28/11/2007, 11h32
  5. Arreter un thread qui "bloque" sur un socket
    Par J-F dans le forum Concurrence et multi-thread
    Réponses: 2
    Dernier message: 12/12/2006, 00h04

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