Java Reference
In-Depth Information
}
}
Returning Object Information Across a Network Connection
Problem
You need to return an object across a network connection.
Solution
Create the object you need, and write it using an ObjectOutputStream created on top of the
socket's output stream.
Discussion
The program in Example 13-7 in the previous chapter reads a Date object over an Ob-
jectInputStream . Example 16-5 , the DaytimeObjectServer (the other end of that pro-
cess), is a program that constructs a Date object each time it's connected to and returns it to
the client.
Example 16-5. DaytimeObjectServer.java
public
public class
DaytimeObjectServer {
/** The TCP port for the object time service. */
public
class DaytimeObjectServer
public static
static final
final short
short TIME_PORT = 1951 ;
public
public static
void main ( String [] argv ) {
ServerSocket sock ;
Socket clientSock ;
try
static void
try {
sock = new
new ServerSocket ( TIME_PORT );
while
while (( clientSock = sock . accept ()) != null
null ) {
System . out . println ( "Accept from " +
clientSock . getInetAddress ());
ObjectOutputStream os = new
new ObjectOutputStream (
clientSock . getOutputStream ());
// Construct and write the Object
os . writeObject ( new
new Date ());
Search WWH ::




Custom Search