Java Reference
In-Depth Information
}
catch
catch
(
UnknownHostException e
) {
System
.
err
.
println
(
server_name
+
" Unknown host"
);
return
return
;
}
catch
catch
(
NoRouteToHostException e
) {
System
.
err
.
println
(
server_name
+
" Unreachable"
);
return
return
;
}
catch
catch
(
ConnectException e
) {
System
.
err
.
println
(
server_name
+
" connect refused"
);
return
return
;
}
catch
catch
(
java
.
io
.
IOException
e
) {
System
.
err
.
println
(
server_name
+
' '
+
e
.
getMessage
());
return
return
;
}
}
}
Reading and Writing Textual Data
Problem
Having connected, you wish to transfer textual data.
Solution
Construct a
BufferedReader
or
PrintWriter
from the socket's
getInputStream()
or
getOutputStream()
.
Discussion
The
Socket
class has methods that allow you to get an
InputStream
or
OutputStream
to
read from or write to the socket. It has no method to fetch a
Reader
or
Writer
, partly be-
cause some network services are limited to ASCII, but mainly because the
Socket
class was
decided on before there were
Reader
and
Writer
classes. You can always create a
Reader
from an
InputStream
or a
Writer
from an
OutputStream
using the conversion classes. The
paradigm for the two most common forms is: