11//: network/ChatterClient.java
22// ©2015 MindView LLC: see Copyright.txt
3- // {TimeOutDuringTesting }
4- // Tests the ChatterServer by starting multiple
3+ // {ValidateByHand }
4+ // Tests the ChatterServer by starting multiple
55// clients, each of which sends datagrams.
66import java .net .*;
77import java .io .*;
8+ import net .mindview .util .*;
89
910public class ChatterClient extends Thread {
1011 // Can listen & send on the same socket:
1112 private DatagramSocket s ;
1213 private InetAddress hostAddress ;
1314 private byte [] buf = new byte [1000 ];
14- private DatagramPacket dp =
15+ private DatagramPacket dp =
1516 new DatagramPacket (buf , buf .length );
1617 private int id ;
1718
@@ -20,7 +21,7 @@ public ChatterClient(int identifier) {
2021 try {
2122 // Auto-assign port number:
2223 s = new DatagramSocket ();
23- hostAddress =
24+ hostAddress =
2425 InetAddress .getByName ("localhost" );
2526 } catch (UnknownHostException e ) {
2627 System .err .println ("Cannot find host" );
@@ -29,36 +30,37 @@ public ChatterClient(int identifier) {
2930 System .err .println ("Can't open socket" );
3031 e .printStackTrace ();
3132 System .exit (1 );
32- }
33+ }
3334 System .out .println ("ChatterClient starting" );
3435 }
35- @ Override
36- public void run () {
36+ public void sendAndEcho (String msg ) {
3737 try {
38- for (int i = 0 ; i < 25 ; i ++) {
39- String outMessage = "Client #" +
40- id + ", message #" + i ;
41- // Make and send a datagram:
42- s .send (Dgram .toDatagram (outMessage ,
43- hostAddress ,
44- ChatterServer .INPORT ));
45- // Block until it echoes back:
46- s .receive (dp );
47- // Print out the echoed contents:
48- String rcvd = "Client #" + id +
49- ", rcvd from " +
50- dp .getAddress () + ", " +
51- dp .getPort () + ": " +
52- Dgram .toString (dp );
53- System .out .println (rcvd );
54- }
38+ // Make and send a datagram:
39+ s .send (Dgram .toDatagram (msg ,
40+ hostAddress ,
41+ ChatterServer .INPORT ));
42+ // Block until it echoes back:
43+ s .receive (dp );
44+ // Print out the echoed contents:
45+ String rcvd = "Client #" + id +
46+ ", rcvd from " +
47+ dp .getAddress () + ", " +
48+ dp .getPort () + ": " +
49+ Dgram .toString (dp );
50+ System .out .println (rcvd );
5551 } catch (IOException e ) {
5652 e .printStackTrace ();
5753 System .exit (1 );
5854 }
5955 }
56+ @ Override
57+ public void run () {
58+ for (int i = 0 ; i <= 25 ; i ++)
59+ sendAndEcho ("Client #" + id + ", message #" + i );
60+ }
6061 public static void main (String [] args ) {
61- for (int i = 0 ; i < 10 ; i ++)
62+ new TimedAbort (5 ); // Terminate after 5 seconds
63+ for (int i = 0 ; i <= 10 ; i ++)
6264 new ChatterClient (i ).start ();
6365 }
6466} ///:~
0 commit comments