OnJava8-Examples/network/ChatterClient.java

67 lines
1.8 KiB
Java
Raw Normal View History

2015-05-05 11:20:13 -07:00
//: network/ChatterClient.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-05-31 18:34:12 -07:00
// {ValidateByHand}
// Tests the ChatterServer by starting multiple
2015-05-05 11:20:13 -07:00
// clients, each of which sends datagrams.
import java.net.*;
import java.io.*;
2015-05-31 18:34:12 -07:00
import net.mindview.util.*;
2015-05-05 11:20:13 -07:00
public class ChatterClient extends Thread {
// Can listen & send on the same socket:
private DatagramSocket s;
private InetAddress hostAddress;
private byte[] buf = new byte[1000];
2015-05-31 18:34:12 -07:00
private DatagramPacket dp =
2015-05-05 11:20:13 -07:00
new DatagramPacket(buf, buf.length);
private int id;
public ChatterClient(int identifier) {
id = identifier;
try {
// Auto-assign port number:
s = new DatagramSocket();
2015-05-31 18:34:12 -07:00
hostAddress =
2015-05-05 11:20:13 -07:00
InetAddress.getByName("localhost");
} catch(UnknownHostException e) {
System.err.println("Cannot find host");
System.exit(1);
} catch(SocketException e) {
System.err.println("Can't open socket");
e.printStackTrace();
System.exit(1);
2015-05-31 18:34:12 -07:00
}
2015-05-05 11:20:13 -07:00
System.out.println("ChatterClient starting");
}
2015-05-31 18:34:12 -07:00
public void sendAndEcho(String msg) {
2015-05-05 11:20:13 -07:00
try {
2015-05-31 18:34:12 -07:00
// Make and send a datagram:
s.send(Dgram.toDatagram(msg,
hostAddress,
ChatterServer.INPORT));
// Block until it echoes back:
s.receive(dp);
// Print out the echoed contents:
String rcvd = "Client #" + id +
", rcvd from " +
dp.getAddress() + ", " +
dp.getPort() + ": " +
Dgram.toString(dp);
System.out.println(rcvd);
2015-05-05 11:20:13 -07:00
} catch(IOException e) {
e.printStackTrace();
System.exit(1);
}
}
2015-05-31 18:34:12 -07:00
@Override
public void run() {
for(int i = 0; i <= 25; i++)
sendAndEcho("Client #" + id + ", message #" + i);
}
2015-05-05 11:20:13 -07:00
public static void main(String[] args) {
2015-05-31 18:34:12 -07:00
new TimedAbort(5); // Terminate after 5 seconds
for(int i = 0; i <= 10; i++)
2015-05-05 11:20:13 -07:00
new ChatterClient(i).start();
}
} ///:~