2016-09-06 12:32:51 -06:00
|
|
|
// network/SimpleClient2.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 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.
|
2016-09-03 13:24:33 -06:00
|
|
|
package network;
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.net.*;
|
|
|
|
import java.io.*;
|
|
|
|
|
2016-09-06 12:32:51 -06:00
|
|
|
public class SimpleClient2 implements Runnable {
|
2016-09-03 12:18:15 -06:00
|
|
|
private InetAddress address;
|
2015-06-15 17:47:35 -07:00
|
|
|
private static int counter = 0;
|
|
|
|
private int id = counter++;
|
|
|
|
private static int threadcount = 0;
|
|
|
|
public static int threadCount() {
|
|
|
|
return threadcount;
|
|
|
|
}
|
2016-09-06 12:32:51 -06:00
|
|
|
public SimpleClient2(InetAddress address) {
|
2015-06-15 17:47:35 -07:00
|
|
|
System.out.println("Making client " + id);
|
2016-09-03 12:18:15 -06:00
|
|
|
this.address = address;
|
2015-06-15 17:47:35 -07:00
|
|
|
threadcount++;
|
2016-09-03 12:18:15 -06:00
|
|
|
}
|
|
|
|
@Override
|
|
|
|
public void run() {
|
|
|
|
try (
|
|
|
|
Socket socket =
|
2016-09-06 12:32:51 -06:00
|
|
|
new Socket(address, ServeOne.PORT);
|
2016-09-03 12:18:15 -06:00
|
|
|
BufferedReader in =
|
2015-06-15 17:47:35 -07:00
|
|
|
new BufferedReader(
|
|
|
|
new InputStreamReader(
|
|
|
|
socket.getInputStream()));
|
2016-09-03 12:18:15 -06:00
|
|
|
PrintWriter out =
|
2015-06-15 17:47:35 -07:00
|
|
|
new PrintWriter(
|
|
|
|
new BufferedWriter(
|
|
|
|
new OutputStreamWriter(
|
2016-09-03 12:18:15 -06:00
|
|
|
// Enable auto-flush:
|
|
|
|
socket.getOutputStream())), true)
|
|
|
|
) {
|
|
|
|
for (int i = 0; i < 25; i++) {
|
2015-06-15 17:47:35 -07:00
|
|
|
out.println("Client " + id + ": " + i);
|
|
|
|
String str = in.readLine();
|
|
|
|
System.out.println(str);
|
|
|
|
}
|
|
|
|
out.println("END");
|
2016-09-03 12:18:15 -06:00
|
|
|
} catch (IOException ex) {
|
|
|
|
throw new RuntimeException(ex);
|
2015-06-15 17:47:35 -07:00
|
|
|
} finally {
|
|
|
|
threadcount--; // Ending this thread
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|