blob: 4b99b0bc370488a0a0753e8855086ec9196099a6 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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());
}
}
}
|