Java Reference
In-Depth Information
3. Receive and print out a text-encoded message: lines 15-19
4. Send a binary-encoded message: lines 21-25
Note that before sending, we add 10 cents to the unit price given in the original message.
To demonstrate the use of the encoding and decoding classes with datagrams, we include
a simple UDP sender and receiver. Since this is very similar to the TCP code, we do not include
any code description.
SendUDP.java
0 import java.net.*; // for DatagramSocket, DatagramPacket, and InetAddress
1 import java.io.*;
// for IOException
2
3 public class SendUDP {
4
5
public static void main(String args[]) throws Exception {
6
7
if (args.length != 2 && args.length != 3) // Test for correct # of args
8
throw new IllegalArgumentException("Parameter(s): <Destination>" +
9
" <Port> [<encoding]");
10
11
InetAddress destAddr = InetAddress.getByName(args[0]); // Destination address
12
int destPort = Integer.parseInt(args[1]);
// Destination port
13
14
ItemQuote quote = new ItemQuote(1234567890987654L, "5mm Super Widgets",
15
1000, 12999, true, false);
16
17
DatagramSocket sock = new DatagramSocket(); // UDP socket for sending
18
19
ItemQuoteEncoder encoder = (args.length == 3 ?
20
new ItemQuoteEncoderText(args[2]) :
21
new ItemQuoteEncoderText());
22
23
byte[] codedQuote = encoder.encode(quote);
24
25
DatagramPacket message = new DatagramPacket(codedQuote, codedQuote.length,
26
destAddr, destPort);
27
sock.send(message);
28
29
sock.close();
30
}
31 }
SendUDP.java
 
Search WWH ::




Custom Search