简体   繁体   中英

Byte buffer transfer via UDP

您能否提供一个通过UDP数据报在两个Java类之间传输的字节缓冲区的示例?

Hows' this ?

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);
    }
}

@none

The DatagramSocket classes sure need a polish up, DatagramChannel is slightly better for clients, but confusing for server programming. For example:

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));
    }
}

Bring on JSR-203 I say

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM