Java Reference
In-Depth Information
System
.
err
.
println
(
e
);
}
}
}
The second example, shown in
Example 13-5
,
shows both reading and writing on the same
socket. The
Echo
server simply echoes back whatever lines of text you send it. It's not a very
clever server, but it is a useful one. It helps in network testing and also in testing clients of
this type!
The
converse()
method holds a short conversation with the
Echo
server on the named host;
program is running on.”
Example 13-5. EchoClientOneLine.java
public
public class
EchoClientOneLine
{
/** What we send across the net */
String mesg
=
"Hello across the net"
;
class
EchoClientOneLine
public
public static
void
main
(
String
[]
argv
) {
iif
(
argv
.
length
==
0
)
new
static
void
new
EchoClientOneLine
().
converse
(
"localhost"
);
else
else
new
new
EchoClientOneLine
().
converse
(
argv
[
0
]);
}
/** Hold one conversation across the net */
protected
protected
void
void
converse
(
String hostName
) {
try
try
{
Socket sock
=
new
new
Socket
(
hostName
,
7
);
// echo server.
BufferedReader is
=
new
new
InputStreamReader
(
sock
.
getInputStream
()));
PrintWriter os
=
new
new
BufferedReader
(
new
true
);
// Do the CRLF ourself since println appends only a \r on
// platforms where that is the native line ending.
os
.
print
(
mesg
+
"\r\n"
);
os
.
flush
();
String reply
=
is
.
readLine
();
System
.
out
.
println
(
"Sent \""
+
mesg
+
"\""
);
System
.
out
.
println
(
"Got \""
+
reply
+
"\""
);
}
catch
new
PrintWriter
(
sock
.
getOutputStream
(),
true
catch
(
IOException e
) {
System
.
err
.
println
(
e
);
}
}
}