Java Reference
In-Depth Information
Compile Listing 9-4 ( javac DGServer.java ) and run the application ( java
DGClient ).Youshouldobserveoutputthat'sthesameasorsimilartothatshownhere:
Server is starting
Send buffer size = 8192
Receive buffer size = 8192
Listing 9-5 demonstrates DatagramPacket and DatagramSocket in a client
context.
Listing 9-5. Sending a datagram packet to and receiving it back from a server
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
class DGClient
{
final static int PORT = 10000;
final static String ADDR = "localhost";
public static void main(String[] args)
{
System.out.println("client is starting");
DatagramSocket s = null;
try (DatagramSocket dgs = new DatagramSocket())
{
byte[] buffer;
buffer = "send me a datagram".getBytes();
InetAddress ia = InetAddress.getByName(ADDR);
DatagramPacket dgp = new DatagramPacket(buffer,
buffer.length, ia,
PORT);
dgs.send(dgp);
byte[] buffer2 = new byte[100];
dgp = new DatagramPacket(buffer2, buffer.length,
ia, PORT);
Search WWH ::




Custom Search