Question

Pouvez-vous fournir un exemple de tampon d'octets transféré entre deux classes java via un datagramme UDP?

Était-ce utile?

La solution

Comment ça?

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;


public class Server {

    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(new InetSocketAddress(5000));
        byte[] message = new byte[512];
        DatagramPacket packet = new DatagramPacket(message, message.length);
        socket.receive(packet);
        System.out.println(new String(packet.getData(), packet.getOffset(), packet.getLength()));
    }
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;


public class Client {

    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket();
        socket.connect(new InetSocketAddress(5000));
        byte[] message = "Oh Hai!".getBytes();
        DatagramPacket packet = new DatagramPacket(message, message.length);
        socket.send(packet);
    }
}

Autres conseils

@none

Les classes DatagramSocket ont certainement besoin d'être peaufinées, DatagramChannel est légèrement meilleur pour les clients, mais déroutant pour la programmation serveur. Par exemple:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;


public class Client {

    public static void main(String[] args) throws IOException {
        DatagramChannel channel = DatagramChannel.open();
        ByteBuffer buffer = ByteBuffer.wrap("Oh Hai!".getBytes());
        channel.send(buffer, new InetSocketAddress("localhost", 5000));
    }
}

Ajoutez JSR-203 . dire

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top