Академический Документы
Профессиональный Документы
Культура Документы
CHAPTER 3
User Datagram Protocol
Writing a client:
You don't care what the local port is, so you call a constructor that lets
the system assign an unused port (an anonymous port).
This port number is placed in any outgoing datagrams and will be used
by the server to address any response datagrams.
opening a datagram socket
DatagramSocket socket = new DatagramSocket(0);
Note: You only specify a local port to connect to. The socket does not know the
remote host or address. By specifying port 0 you ask Java to pick a random available
port for you, much as with server sockets.
Writing a server:
Clients need to know on which port the server is listening for incoming
datagrams.
When a server constructs a DatagramSocket, it must specify the local
port on which it will listen.
A UDP server follows almost the same pattern as a UDP client, except
that you usually receive before sending and dont choose an
anonymous port to bind to.
opening a datagram socket on a well-known port 13:
DatagramSocket socket = new DatagramSocket(13);
DatagramPacket
To send data, put the data in a DatagramPacket and send the packet using a
DatagramSocket. To receive data, take a DatagramPacket object from a
DatagramSocket and then inspect the contents of the packet. UDP datagram is
represented by an instance of the DatagramPacket class:
public final class DatagramPacket extends Object
Lab activity:
1. Create the classes using Java program
2. Create a java program to listen for UDP packets
3. Create a java program to send and receive file.
4. Create the application of multicast socket