forked from ZhiqingXiao/java-book
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chapter26.java
407 lines (319 loc) · 10.2 KB
/
chapter26.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
// Demonstrate InetAddress.
import java.net.*;
class InetAddressDemo {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("www.mcgraw-hill.com");
System.out.println("Host name: " + address.getHostName());
System.out.println("Address: " + address.getHostAddress());
System.out.println();
address = InetAddress.getByName("www.mhhe.com");
System.out.println("Host name: " + address.getHostName());
System.out.println("Address: " + address.getHostAddress());
System.out.println();
address = InetAddress.getByName("www.mheducation.com");
System.out.println("Host name: " + address.getHostName());
System.out.println("Address: " + address.getHostAddress());
} catch (UnknownHostException exc) {
System.out.println(exc);
}
}
}
// -----------------------------------------
// Demonstrate Sockets.
import java.net.*;
import java.io.*;
class SocketDemo {
public static void main(String[] args) {
int ch;
Socket socket = null;
try {
// Create a socket connected to whois.internic.net, port 43.
socket = new Socket("whois.internic.net", 43);
// Obtain input and output streams.
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
// Construct a request string.
String str = (args.length == 0 ? "mcgraw-hill.com" :
args[0]) + "\n";
// Convert to bytes.
byte[] buf = str.getBytes();
// Send request.
out.write(buf);
// Read and display response.
while ((ch = in.read()) != -1) {
System.out.print((char) ch);
}
} catch(IOException exc) {
System.out.println(exc);
} finally {
try {
if(socket != null) socket.close();
} catch(IOException exc) {
System.out.println("Error closing socket: " + exc);
}
}
}
}
// -----------------------------------------
// Use automatic resource management to close a socket.
import java.net.*;
import java.io.*;
class SocketDemo {
public static void main(String[] args) {
int ch;
// Create a socket connected to internic.net, port 43. Manage this
// socket with a try-with-resources block.
try ( Socket socket = new Socket("whois.internic.net", 43) ) {
// Obtain input and output streams.
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
// Construct a request string.
String str = (args.length == 0 ? "mcgraw-hill.com" :
args[0]) + "\n";
// Convert to bytes.
byte[] buf = str.getBytes();
// Send request.
out.write(buf);
// Read and display response.
while ((ch = in.read()) != -1) {
System.out.print((char) ch);
}
} catch(IOException exc) {
System.out.println(exc);
}
// The socket is now closed.
}
}
// -----------------------------------------
// Demonstrate URL.
import java.net.*;
class URLDemo {
public static void main(String[] args) {
try {
URL url = new URL("http://www.mhhe.com:80/index.html");
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Port: " + url.getPort());
System.out.println("Host: " + url.getHost());
System.out.println("File: " + url.getFile());
} catch (MalformedURLException exc) {
System.out.println("Invalid URL: " + exc);
}
}
}
// -----------------------------------------
// Demonstrate URLConnection.
import java.net.*;
import java.io.*;
import java.util.*;
class UCDemo
{
public static void main(String[] args) {
InputStream in = null;
URLConnection connection = null;
try {
URL url = new URL("http://www.mcgraw-hill.com");
connection = url.openConnection();
// get date
long d = connection.getDate();
if(d==0)
System.out.println("No date information.");
else
System.out.println("Date: " + new Date(d));
// get content type
System.out.println("Content-Type: " +
connection.getContentType());
// get expiration date
d = connection.getExpiration();
if(d==0)
System.out.println("No expiration information.");
else
System.out.println("Expires: " + new Date(d));
// get last-modified date
d = connection.getLastModified();
if(d==0)
System.out.println("No last-modified information.");
else
System.out.println("Last-Modified: " + new Date(d));
// get content length
long len = connection.getContentLengthLong();
if(len == -1)
System.out.println("Content length unavailable.");
else
System.out.println("Content-Length: " + len);
if(len != 0) {
System.out.println("=== Content ===");
in = connection.getInputStream();
int ch;
while (((ch = in.read()) != -1)) {
System.out.print((char) ch);
}
} else {
System.out.println("No content available.");
}
} catch(IOException exc) {
System.out.println("Connection Error: " + exc);
} finally {
try {
if(in != null) in.close();
} catch(IOException exc) {
System.out.println("Error closing connection: " + exc);
}
}
}
}
// -----------------------------------------
import java.net.*;
import java.io.*;
class GetFileFromSite {
public static void main(String[] args) {
if(args.length != 2) {
System.out.println("Usage: java GetFileFromSite url file");
return;
}
InputStream in = null;
URLConnection connection = null;
FileOutputStream fout = null;
try {
URL url = new URL(args[0]);
connection = url.openConnection();
in = connection.getInputStream();
fout = new FileOutputStream(args[1]);
// Download and save the file.
int b;
while (((b = in.read()) != -1)) {
fout.write(b);
}
} catch (IOException exc) {
System.out.println("Connection Error: " + exc);
} finally {
try {
if(in != null) in.close();
if(fout != null) fout.close();
} catch (IOException exc) {
System.out.println("Error closing stream: " + exc);
}
}
}
}
// -----------------------------------------
// Demonstrate HttpURLConnection.
import java.net.*;
import java.io.*;
import java.util.*;
class HttpURLConnectionDemo
{
public static void main(String[] args) {
try {
URL url = new URL("http://www.mcgraw-hill.com");
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
// Display request method.
System.out.println("Request method is " +
connection.getRequestMethod());
// Display response code.
System.out.println("Response code is " +
connection.getResponseCode());
// Display response message.
System.out.println("Response Message is " +
connection.getResponseMessage());
// Get a list of the header fields and a set
// of the header keys.
Map<String, List<String>> hdrMap = connection.getHeaderFields();
Set<String> hdrKeys = hdrMap.keySet();
System.out.println("\nHere is the header:");
// Display all header keys and values.
for(String k : hdrKeys) {
System.out.println("Key: " + k +
" Value: " + hdrMap.get(k));
}
} catch(IOException exc) {
System.out.println(exc);
}
}
}
// -----------------------------------------
// Demonstrate datagrams -- server side.
import java.net.*;
import java.io.*;
class DGServer {
// These ports were chosen arbitrarily. You must use
// unused ports on your machine.
public static int clientPort = 50000;
public static int serverPort = 50001;
public static DatagramSocket ds;
public static void dgServer() throws IOException {
byte[] buffer;
String str;
BufferedReader conin = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter characters. Enter 'stop' to quit.");
for(;;) {
// read a string from the keyboard
str = conin.readLine();
// convert string to byte array for transmission
buffer = str.getBytes();
// send a new packet that contains the string
ds.send(new DatagramPacket(buffer, buffer.length,
InetAddress.getLocalHost(), clientPort));
// quit when "stop" is entered
if(str.equals("stop")) {
System.out.println("Server Quits.");
return;
}
}
}
public static void main(String[] args) {
ds = null;
try {
ds = new DatagramSocket(serverPort);
dgServer();
} catch(IOException exc) {
System.out.println("Communication error: " + exc);
} finally {
if(ds != null) ds.close();
}
}
}
// -----------------------------------------
// Demonstrate datagrams -- client side.
import java.net.*;
import java.io.*;
class DGClient {
// This ports was choosen arbitrarily. You must use
// an unused port on your machine.
public static int clientPort = 50000;
public static int buffer_size = 1024;
public static DatagramSocket ds;
public static void dgClient() throws IOException {
String str;
byte[] buffer = new byte[buffer_size];
System.out.println("Receiving Data");
for(;;) {
// create a new packet to receive the data
DatagramPacket p = new DatagramPacket(buffer, buffer.length);
// wait for a packet
ds.receive(p);
// convert buffer into String
str = new String(p.getData(), 0, p.getLength());
// display the string on the client
System.out.println(str);
// quit when "stop" is received.
if(str.equals("stop")) {
System.out.println("Client Stopping.");
break;
}
}
}
public static void main(String[] args) {
ds = null;
try {
ds = new DatagramSocket(clientPort);
dgClient();
} catch(IOException exc) {
System.out.println("Communication error: " + exc);
} finally {
if(ds != null) ds.close();
}
}
}