Java Reference
In-Depth Information
that instance (to reflect the number of bytes in the received message). Applications that call
receive()
more than once with the same instance of
DatagramPacket
should explicitly reset the
internal length to the actual buffer length before each subsequent call to
receive()
.
Another potential source of problems for beginners is the
getData()
method of
Data−
gramPacket
, which always returns the entire original buffer, ignoring the internal offset and
length values. Receiving a message into the
DatagramPacket
only modifies those locations of
the buffer into which message data was placed. For example, suppose
buf
is a byte array of
size 20, which has been initialized so that each byte contains its index in the array:
0
12 3
4
56 7
89 011
12
13
14
15
16
17
18
19
Suppose also that
dg
is a
DatagramPacket
, and that we set
dg
's buffer to be the middle 10 bytes
of
buf
:
dg.setData(buf,5,10);
Now suppose that
dgsocket
is a
DatagramSocket
, and that somebody sends an 8-byte message
containing
41
42
43
44
45
46
47
48
to
dgsocket
. The message is received into
dg
:
dgsocket.receive(dg);
Now, calling
dg.getData()
returns a reference to the original byte array
buf
, whose contents
are now
0
12
3
41
42
44
45
46
13
15
16
18
19
4
43
47
48
14
17
Note that only bytes 5-12 of
buf
have been modified and that, in general, the application
needs to use
getOffset()
and
getData()
to access just the received data. One possibility is to
copy the received data into a separate byte array, like this:
byte[] destBuf = new byte[dg.getLength()];
System.arraycopy(dg.getData(), dg.getOffset(), destBuf, 0, destBuf.length);
2.4
Exercises
1. For
TCPEchoServer.java
, we explicitly specify the port to the socket in the constructor.
We said that a socket must have a port for communication, yet we do not specify a port
in
TCPEchoClient.java
. How is the echo client's socket assigned a port?
2. When you make a phone call, it is usually the callee that answers with “Hello.” What
changes to our client and server examples would be needed to implement this?
3. What happens if a TCP server never calls
accept()
? What happens if a TCP client sends
data on a socket that has not yet been
accept()
ed at the server?
Search WWH ::
Custom Search