see title?
views:
1024answers:
3Can you provide an example of a byte buffer transferred between two java classes via UDP datagram?
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); } }
OP: Well, it is student work, but it's a tiny part of a much bigger project. I'm more testing the efficacy of the site than I am stuck for an answer, also to test the site as many questions are so much broader than one might expect.
My implementation only gets the first byte, the rest are unset, but I haven't done any significant diganostics yet.
UDP is necessary by design, it's streaming over an unreliable link.
Amazingly fast answer though, from Dave, very impressed. Even looking at that I think from memory perhaps my code has new DatagramPacket(outbuf,1,dest,port); or something similar.... That'd do it! blush
Thanks all!
@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