OnJava8-Examples/network/SimpleClient2.java

51 lines
1.4 KiB
Java
Raw Normal View History

// network/SimpleClient2.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.
package network;
2015-06-15 17:47:35 -07:00
import java.net.*;
import java.io.*;
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;
}
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 =
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)
) {
2017-01-20 21:30:44 -08:00
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
}
}
}