OnJava8-Examples/network/ChatterClient.java

49 lines
1.4 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// network/ChatterClient.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
// Starts multiple clients, each of which sends datagrams.
package network;
2015-06-15 17:47:35 -07:00
import java.net.*;
import java.io.*;
public class ChatterClient implements Runnable {
2015-06-15 17:47:35 -07:00
private InetAddress hostAddress;
private byte[] buf = new byte[1000];
private DatagramPacket dp =
new DatagramPacket(buf, buf.length);
private static int counter = 0;
private int id = counter++;
2015-06-15 17:47:35 -07:00
public ChatterClient(InetAddress hostAddress) {
this.hostAddress = hostAddress;
System.out.println("ChatterClient #" + id + " starting");
2015-06-15 17:47:35 -07:00
}
public void sendAndEcho(String msg) {
2016-09-03 12:17:25 -06:00
try (
// Auto-assign port number:
DatagramSocket s = new DatagramSocket();
) {
2015-06-15 17:47:35 -07:00
// Make and send a datagram:
2016-08-31 12:30:03 -06:00
s.send(Dgram.toDatagram(
msg, hostAddress, ChatterServer.INPORT));
2015-06-15 17:47:35 -07:00
// Block until it echoes back:
s.receive(dp);
2016-08-31 12:30:03 -06:00
// Display the echoed contents:
2015-06-15 17:47:35 -07:00
String rcvd = "Client #" + id +
", rcvd from " +
dp.getAddress() + ", " +
dp.getPort() + ": " +
Dgram.toString(dp);
System.out.println(rcvd);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void run() {
for(int i = 0; i <= 5; i++)
2015-06-15 17:47:35 -07:00
sendAndEcho("Client #" + id + ", message #" + i);
}
2015-09-07 11:44:36 -06:00
}