summaryrefslogtreecommitdiffstats
path: root/Master/Reference Architectures and Patterns/hjp5/examples/EchoClient.java
diff options
context:
space:
mode:
Diffstat (limited to 'Master/Reference Architectures and Patterns/hjp5/examples/EchoClient.java')
-rw-r--r--Master/Reference Architectures and Patterns/hjp5/examples/EchoClient.java95
1 files changed, 95 insertions, 0 deletions
diff --git a/Master/Reference Architectures and Patterns/hjp5/examples/EchoClient.java b/Master/Reference Architectures and Patterns/hjp5/examples/EchoClient.java
new file mode 100644
index 0000000..4b99b0b
--- /dev/null
+++ b/Master/Reference Architectures and Patterns/hjp5/examples/EchoClient.java
@@ -0,0 +1,95 @@
+/* EchoClient.java */
+
+import java.net.*;
+import java.io.*;
+
+public class EchoClient
+{
+ public static void main(String[] args)
+ {
+ if (args.length != 1) {
+ System.err.println("Usage: java EchoClient <host>");
+ System.exit(1);
+ }
+ try {
+ Socket sock = new Socket(args[0], 7);
+ InputStream in = sock.getInputStream();
+ OutputStream out = sock.getOutputStream();
+ //Timeout setzen
+ sock.setSoTimeout(300);
+ //Ausgabethread erzeugen
+ OutputThread th = new OutputThread(in);
+ th.start();
+ //Schleife für Benutzereingaben
+ BufferedReader conin = new BufferedReader(
+ new InputStreamReader(System.in));
+ String line = "";
+ while (true) {
+ //Eingabezeile lesen
+ line = conin.readLine();
+ if (line.equalsIgnoreCase("QUIT")) {
+ break;
+ }
+ //Eingabezeile an ECHO-Server schicken
+ out.write(line.getBytes());
+ out.write('\r');
+ out.write('\n');
+ //Ausgabe abwarten
+ th.yield();
+ }
+ //Programm beenden
+ System.out.println("terminating output thread...");
+ th.requestStop();
+ th.yield();
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ }
+ in.close();
+ out.close();
+ sock.close();
+ } catch (IOException e) {
+ System.err.println(e.toString());
+ System.exit(1);
+ }
+ }
+}
+
+class OutputThread
+extends Thread
+{
+ InputStream in;
+ boolean stoprequested;
+
+ public OutputThread(InputStream in)
+ {
+ super();
+ this.in = in;
+ stoprequested = false;
+ }
+
+ public synchronized void requestStop()
+ {
+ stoprequested = true;
+ }
+
+ public void run()
+ {
+ int len;
+ byte[] b = new byte[100];
+ try {
+ while (!stoprequested) {
+ try {
+ if ((len = in.read(b)) == -1) {
+ break;
+ }
+ System.out.write(b, 0, len);
+ } catch (InterruptedIOException e) {
+ //nochmal versuchen
+ }
+ }
+ } catch (IOException e) {
+ System.err.println("OutputThread: " + e.toString());
+ }
+ }
+} \ No newline at end of file