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 :

Java NIO UDP


Sujet :

Entrée/Sortie Java

  1. #1
    Membre chevronné

    Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Novembre 2009
    Messages
    377
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Novembre 2009
    Messages : 377
    Par défaut Java NIO UDP
    Bonjour,

    j'ai quelques soucis a implémenter correctement un java NIO en udp avec un selector.

    Voila ou j'en suis :

    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
    public final class NetworkManager {
     
        DatagramChannel channel = null;
        private final static int BUFFER_SIZE = 1024;    
        protected Selector selector;
     
        InetSocketAddress isa ;
        /**
         * Create a network manager with any port allocated by the OS.
         */
        public NetworkManager() {
            this.isa = new InetSocketAddress(0);
        }
     
        public NetworkManager(InetSocketAddress isa) {
            this.isa = isa;
        }
     
        protected void initChannel() throws IOException 
        {
            // Prepare the channel.
            channel = DatagramChannel.open();
            channel.configureBlocking(false);
            // Connect udp channel.
     
            channel.bind(new InetSocketAddress(isa.getPort()));
     
            // Prepare the selector.
            selector = Selector.open();
            int interestSet = SelectionKey.OP_READ; 
            channel.register(selector, interestSet);
        }
     
        public void send(DatagramPacket sendMessage) throws IOException {
            if (channel == null) {
                initChannel();
            }
            ByteBuffer bb = ByteBuffer.wrap(sendMessage.getData());
            channel.send(bb, sendMessage.getSocketAddress());
        }
     
        private RawMessage read(SelectionKey key) throws IOException {
            DatagramChannel chan = (DatagramChannel) key.channel();
            ByteBuffer readBuffer = ByteBuffer.allocate(BUFFER_SIZE);
            // Exception se produit ici !!
            chan.read(readBuffer);
            RawMessage rawMessage = getRawMessage(chan.getRemoteAddress(), readBuffer);
            return rawMessage;
        }
     
        /**
         * Wait until a message comming. Blocked method.
         *
         * @return A raw message from the channel or null if wake up.
         * @throws IOException
         */
        public RawMessage receive() throws IOException {
            if (channel == null) {
                initChannel();
            }
            selector.select();
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> itSelectkey = selector.selectedKeys().iterator();
            while (itSelectkey.hasNext()) {
                SelectionKey key = itSelectkey.next();
                if (key.isReadable()) 
                {
                    return read(key);
                }
            }
            return null;
        }
     
        /**
         * Wake up the selector, selector is used in receive() method who is
         * blocking.
         */
        public void wakeUp() {
            selector.wakeup();
        }
    Le soucis est que lorsque j'arrive dans la méthode read, il me dit que le channel est non connecté :

    Exception in thread "Thread-1" java.nio.channels.NotYetConnectedException
    at sun.nio.ch.DatagramChannelImpl.read(DatagramChannelImpl.java:551)
    at manager.NetworkManager.read(NetworkManager.java:87)
    at manager.NetworkManager.receive(NetworkManager.java:109)
    at Rct.receive(TS501369Rct.java:99)
    at Main.TS501369Rct$1.run(TS501369Rct.java:77)
    at java.lang.Thread.run(Thread.java:724)
    Et je n'arrive pas à trouver comment effectuer la connexion, en TCP j'aurai fais un connect() et dans le selector j'aurai fait un finishConnect. Mais je trouve pas la solution pour le faire en UDP.

    Merci

  2. #2
    Membre chevronné

    Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Novembre 2009
    Messages
    377
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Novembre 2009
    Messages : 377
    Par défaut
    J'ai finalement trouvé, en utilisant la méthode receive, je n'ai pas besoin d'être connecté. Je reste quand même intéresser par une explication du "connecté" en UDP et pourquoi la méthode read demande de l'être.

  3. #3
    Modérateur

    Profil pro
    Inscrit en
    Septembre 2004
    Messages
    12 579
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2004
    Messages : 12 579
    Par défaut
    Citation Envoyé par manticore Voir le message
    Je reste quand même intéresser par une explication du "connecté" en UDP et pourquoi la méthode read demande de l'être.
    Lire la JavaDoc de DatagramChannel, peut-être ?
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  4. #4
    Membre chevronné

    Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Novembre 2009
    Messages
    377
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Novembre 2009
    Messages : 377
    Par défaut
    Lire la JavaDoc de DatagramChannel, peut-être ?
    Je me suis mal exprimé, le point qui reste obscur est de savoir comment il peut lancer l'exception :
    NotYetConnectedException - If this channel's socket is not connected
    Alors que j'effectue la connexion :
    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
     
    protected void initChannel() throws IOException 
        {
            // Prepare the channel.
            channel = DatagramChannel.open();
            channel.configureBlocking(false);
            // Connect udp channel.
            channel.bind(new InetSocketAddress(isa.getPort()));
            channel.connect(isa);
     
            // Prepare the selector.
            selector = Selector.open();
            int interestSet = SelectionKey.OP_READ; 
            channel.register(selector, interestSet);
        }

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

Discussions similaires

  1. java.nio : utilisation des Channel
    Par jan0 dans le forum Entrée/Sortie
    Réponses: 9
    Dernier message: 23/05/2016, 13h45
  2. socket udp multicast et l'api java.nio
    Par maarek dans le forum Entrée/Sortie
    Réponses: 2
    Dernier message: 01/07/2008, 07h33
  3. Réponses: 3
    Dernier message: 20/10/2006, 19h50
  4. [reseau ] java.nio.channels
    Par AMARI_SALIM dans le forum Entrée/Sortie
    Réponses: 4
    Dernier message: 10/04/2006, 22h43
  5. Réponses: 3
    Dernier message: 22/11/2005, 19h23

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