Java Reference
In-Depth Information
Note
The
Socket
constructor throws a
java.net.UnknownHostException
if the host
cannot be found.
UnknownHostException
31.2.3 Data Transmission through Sockets
After the server accepts the connection, communication between the server and the client is
conducted in the same way as for I/O streams. The statements needed to create the streams and
to exchange data between them are shown in FigureĀ 31.2.
Server
Client
int port = 8000;
int port = 8000;
DataInputStream in;
DataOutputStream out;
ServerSocket server;
Socket socket;
String host = "localhost"
DataInputStream in;
DataOutputStream out;
Socket socket;
Connection
Request
server = new ServerSocket(port);
socket = server.accept();
in = new DataInputStream
(socket.getInputStream());
out = new DataOutStream
(socket.getOutputStream());
System.out.println(in.readDouble());
out.writeDouble(aNumber);
socket = new Socket(host, port);
in = new DataInputStream
(socket.getInputStream());
out = new DataOutputStream
(socket.getOutputStream());
I/O
Streams
out.writeDouble(aNumber);
System.out.println(in.readDouble());
F
IGURE
31.2
The server and client exchange data through I/O streams on top of the socket.
To get an input stream and an output stream, use the
getInputStream()
and
getOutputStream()
methods on a socket object. For example, the following statements
create an
InputStream
stream called
input
and an
OutputStream
stream called
output
from a socket:
InputStream input = socket.getInputStream();
OutputStream output = socket.getOutputStream();
The
InputStream
and
OutputStream
streams are used to read or write bytes. You can
use
DataInputStream
,
DataOutputStream
,
BufferedReader
, and
PrintWriter
to
wrap on the
InputStream
and
OutputStream
to read or write data, such as
int
,
double
,
or
String
. The following statements, for instance, create the
DataInputStream
stream
input
and the
DataOutput
stream
output
to read and write primitive data values:
DataInputStream input =
new
DataInputStream
(socket.getInputStream());
DataOutputStream output =
new
DataOutputStream
(socket.getOutputStream());
The server can use
input.readDouble()
to receive a
double
value from the client and
output.writeDouble(d)
to send the
double
value
d
to the client.
Tip
Recall that binary I/O is more efficient than text I/O because text I/O requires encoding
and decoding. Therefore, it is better to use binary I/O for transmitting data between a
server and a client to improve performance.
Search WWH ::
Custom Search