通过UDP传输字节缓冲区

时间:2008-09-17 04:36:00

标签: java udp datagram

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

2 个答案:

答案 0 :(得分:4)

怎么样?

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

答案 1 :(得分:0)

@none

DatagramSocket类确实需要进行改进,DatagramChannel对于客户端来说稍微好一点,但对于服务器编程来说却很困惑。例如:

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

带上JSR-203我说