Skip to content

Commit 11610b8

Browse files
author
Bruce Eckel
committed
Further try-with-resources rewrite
1 parent e6dd219 commit 11610b8

File tree

2 files changed

+11
-15
lines changed

2 files changed

+11
-15
lines changed

network/ChatterClient.java

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,6 @@
1010
import onjava.*;
1111

1212
public class ChatterClient extends Thread {
13-
// Can listen & send on the same socket:
14-
private DatagramSocket s;
1513
private InetAddress hostAddress;
1614
private byte[] buf = new byte[1000];
1715
private DatagramPacket dp =
@@ -21,21 +19,19 @@ public class ChatterClient extends Thread {
2119
public ChatterClient(int identifier) {
2220
id = identifier;
2321
try {
24-
// Auto-assign port number:
25-
s = new DatagramSocket();
2622
hostAddress =
2723
InetAddress.getByName("localhost");
2824
} catch(UnknownHostException e) {
2925
System.err.println("Cannot find host");
3026
System.exit(1);
31-
} catch(SocketException e) {
32-
System.err.println("Can't open socket");
33-
throw new RuntimeException(e);
3427
}
3528
System.out.println("ChatterClient starting");
3629
}
3730
public void sendAndEcho(String msg) {
38-
try {
31+
try (
32+
// Auto-assign port number:
33+
DatagramSocket s = new DatagramSocket();
34+
) {
3935
// Make and send a datagram:
4036
s.send(Dgram.toDatagram(
4137
msg, hostAddress, ChatterServer.INPORT));
@@ -48,6 +44,9 @@ public void sendAndEcho(String msg) {
4844
dp.getPort() + ": " +
4945
Dgram.toString(dp);
5046
System.out.println(rcvd);
47+
} catch(SocketException e) {
48+
System.err.println("Can't open socket");
49+
throw new RuntimeException(e);
5150
} catch(IOException e) {
5251
throw new RuntimeException(e);
5352
}

network/ChatterServer.java

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,12 @@ public class ChatterServer {
1313
private byte[] buf = new byte[1000];
1414
private DatagramPacket dp =
1515
new DatagramPacket(buf, buf.length);
16-
// Can listen & send on the same socket:
17-
private DatagramSocket socket;
1816

1917
public ChatterServer() {
20-
try {
21-
socket = new DatagramSocket(INPORT);
18+
// Can listen & send on the same socket:
19+
try (
20+
DatagramSocket socket = new DatagramSocket(INPORT)
21+
) {
2222
System.out.println("Server started");
2323
while(true) {
2424
// Block until a datagram appears:
@@ -37,9 +37,6 @@ public ChatterServer() {
3737
dp.getAddress(), dp.getPort());
3838
socket.send(echo);
3939
}
40-
} catch(SocketException e) {
41-
System.err.println("Can't open socket");
42-
System.exit(1);
4340
} catch(IOException e) {
4441
System.out.println("Communication error");
4542
throw new RuntimeException(e);

0 commit comments

Comments
 (0)